NestJS
A TypeScript framework of modules, providers and decorators on Express or Fastify, with guards, pipes, interceptors and filters around each handler. Interviewers probe what the decorators hide.
on this pageshowhide
explore
- Module Graph & Providers6 questions
- Env Config & Schemas5 questions
- Route Decorators & Versioning5 questions
- Pipes and Validation6 questions
- Guards and Interceptors5 questions
- Exception Filters and Middleware6 questions
- Request Lifecycle Order5 questions
- Application Lifecycle Hooks5 questions
- Test Modules & E2E5 questions
- Sign-In & Policies15 questions
- Passport & JWT Guards5 questions
- First-Party Auth Module5 questions
- Roles & Policy Guards5 questions
- Microservices and Messaging6 questions
questions
69 · 11 sectionsIn a NestJS 12 app, why can OrdersService not inject PaymentsService from PaymentsModule until that module exports it?
basics
~10 sNest modules encapsulate their providers: OrdersModule can inject only its own providers and those an imported module lists in exports. Until PaymentsModule exports PaymentsService, bootstrap fails with a "Nest can't resolve dependencies" error.
In NestJS, how do useClass, useValue, useFactory and useExisting providers differ, and when must a consumer use @Inject() with a token?
basics
~20 sEach NestJS custom provider maps a token to a value: useClass instantiates a class, useValue registers a ready object, useFactory returns what a function builds from its inject list, and useExisting aliases another token. Non-class tokens need @Inject(token).
In NestJS, what is a dynamic module returned by forRoot() or register(), and what does ConfigurableModuleBuilder generate for you?
basics
~20 sA NestJS dynamic module is a DynamicModule object, @Module metadata plus a required module key, that a static method builds from the caller's options. ConfigurableModuleBuilder generates that method, its Async variant and the options token.
In a NestJS app, OrdersService and PaymentsService inject each other and bootstrap fails. What does Nest report, and how does forwardRef() resolve it?
basics
~20 sNestJS reports a CircularDependencyException, or an undefined dependency at some index when a file-level import cycle hides a class. Wrapping each side's token in @Inject(forwardRef(() => Other)) lets Nest resolve both; module cycles use forwardRef() in imports.
In a NestJS app, a per-tenant connection provider is marked Scope.REQUEST and every endpoint that reaches it gets slower. Why, and what can replace it?
basics
~20 sIn NestJS, Scope.REQUEST bubbles up the injection chain: every provider and controller that depends on the tenant connection becomes request-scoped and is rebuilt per request. Durable providers or a singleton reading tenant context avoid that.
In a NestJS 12 app, what does ConfigModule.forRoot() do with a .env file, and how do other modules get ConfigService?
basics
~20 sConfigModule.forRoot() parses the .env file in the working directory, merges it with process.env (real environment variables win by default) and registers ConfigService. A feature module imports ConfigModule to inject it, unless forRoot set isGlobal: true.
In NestJS 12, how does ConfigModule.forRoot's validationSchema stop the app booting on a missing secret, and what does ConfigService then return?
basics
~20 sIn NestJS 12, forRoot checks the merged .env and process variables against a Standard Schema before any provider is built, throwing 'Config validation error' with every bad variable. ConfigService then returns the schema's coerced output.
In NestJS's @nestjs/config, how do ConfigService.get and ConfigService.getOrThrow differ, and when does each return undefined or throw?
basics
~10 sConfigService.get returns the value, the default you passed, or undefined, and never throws. getOrThrow takes the same arguments but throws a TypeError when the result is still undefined, at the moment it is called.
In NestJS's @nestjs/config, what does registerAs() create, and how do you inject a namespace with ConfigType instead of ConfigService.get?
basics
~10 sregisterAs('mail', factory) tags a configuration factory with a namespace and an injection token, factory.KEY. Load it, then inject the whole object with @Inject(mailConfig.KEY) typed as ConfigType<typeof mailConfig>, or read one value as 'mail.host'.
In a NestJS app, MailModule imports ConfigModule.forFeature(mailConfig), yet another module's constructor reads configService.get('mail.host') and gets undefined; why?
basics
~20 sforFeature merges the namespace into ConfigService's shared configuration through a separate loader provider that nothing depends on, so Nest does not order it before other modules' constructors. Read it in onModuleInit, or inject mailConfig.KEY directly.
In a NestJS controller, how do @Controller, @Get, @Post, @Param, @Query and @Body turn an HTTP request into a handler call?
basics
~20 s@Controller('users') sets a path prefix and @Get(':id') or @Post() adds the HTTP method and sub-path. Nest fills arguments from @Param, @Query and @Body, then sends the return value, as JSON for objects, with status 200, or 201 for POST.
In NestJS, what changes when a route handler injects the response with @Res(), and when do you need @Res({ passthrough: true })?
basics
~20 sInjecting @Res() or @Next() puts the handler in library-specific mode: Nest stops sending its return value, so the handler must write the response or the request hangs. @Res({ passthrough: true }) exposes the native object while Nest still sends the return value.
In NestJS, how does app.enableVersioning() with VersioningType URI, HEADER or MEDIA_TYPE route a request to a @Version('1') or @Version('2') handler?
basics
~20 senableVersioning() makes Nest match the version set by @Controller({ version }) or @Version(). URI, the default, puts /v1 after the global prefix; HEADER reads a named request header; MEDIA_TYPE reads a key such as v= inside Accept. Mismatches return 404.
In a NestJS 12 app on the Express adapter, why does GET /users/me reach the @Get(':id') handler, and how do routeConflictPolicy and routeResolutionStrategy help?
basics
~10 sNest registers routes in declaration order and the Express adapter runs the first match, so an earlier @Get(':id') captures 'me'. NestJS 12's routeConflictPolicy reports this at bootstrap; routeResolutionStrategy: 'specificity' registers literal routes first.
In NestJS, how do you route a tenant sub-domain such as acme.example.com to a controller and read the tenant name with @HostParam?
basics
~10 sPass a host pattern to the controller, @Controller({ host: ':tenant.example.com' }), and read the captured segment with @HostParam('tenant'). Requests whose host name does not match skip that controller's routes, usually ending in a 404.
In NestJS, what is a pipe, what does its transform() method receive, and what happens when it throws?
basics
~20 sA NestJS pipe is an @Injectable class implementing PipeTransform. Its transform(value, metadata) gets one handler argument before the handler runs; what it returns replaces that argument, and if it throws, the handler is skipped and the exception becomes the response.
In NestJS 12, what do ValidationPipe's whitelist, forbidNonWhitelisted and transform options do to a create-order request body?
basics
~20 sIn NestJS 12, ValidationPipe's whitelist strips body properties with no class-validator decorator, forbidNonWhitelisted (alongside it) rejects them with a 400, and transform hands the handler a real DTO instance but does not coerce body fields by itself.
In NestJS, how do ParseIntPipe and DefaultValuePipe handle a page query parameter that is missing, empty or non-numeric?
basics
~20 sParseIntPipe accepts only integer strings or integer numbers and throws a 400 for anything else, including a missing value unless optional: true. DefaultValuePipe, listed before it, swaps null or undefined for a default, but an empty string is not missing.
In NestJS 12, how does StandardSchemaValidationPipe validate @Body({ schema }), and what happens if the pipe is never registered?
basics
~20 sIn NestJS 12, @Body({ schema }) only attaches the schema as metadata. StandardSchemaValidationPipe reads it, calls the schema's ~standard.validate, throws a 400 listing path-prefixed issues, and passes the schema's output on. Without the pipe registered, nothing validates.
A NestJS app has a global ValidationPipe with transform: true, yet GET /orders/abc reaches the handler with id NaN and bulk order arrays go unvalidated. Why?
basics
~20 sValidationPipe validates only class-typed parameters. A number param is merely converted with unary plus, so 'abc' becomes NaN, and a CreateOrderDto[] body reports metatype Array and is skipped. Add ParseIntPipe and ParseArrayPipe({ items: CreateOrderDto }).
In a NestJS 12 app, what does a guard's canActivate() receive and return, and what happens when it denies a request?
basics
~20 sA NestJS guard implements CanActivate: canActivate() receives the ExecutionContext and returns a boolean, or a Promise or Observable of one. A truthy result lets the handler run; a falsy one makes Nest throw ForbiddenException, a 403 'Forbidden resource' response.
In a NestJS 12 interceptor, what does CallHandler.handle() return, and how do you time or reshape a handler's result with RxJS?
basics
~20 snext.handle() returns an RxJS Observable of the route handler's result, and the handler runs only once Nest subscribes to the stream intercept() returns. Code before handle() runs first; operators such as map, finalize and timeout act on the result afterwards.
In NestJS 12, how does a guard read metadata from a Reflector.createDecorator decorator, and when do getAllAndOverride and getAllAndMerge differ?
basics
~10 sInject Reflector and pass it the decorator plus targets from the ExecutionContext. getAllAndOverride(Dec, [context.getHandler(), context.getClass()]) returns the first defined value, so the method overrides the controller; getAllAndMerge concatenates arrays or shallow-merges objects from both.
A NestJS 12 app binds ClassSerializerInterceptor globally and marks UserEntity.password with @Exclude(), yet one endpoint still returns the password; why?
basics
~20 sClassSerializerInterceptor applies class-transformer metadata only to class instances. A handler that returns a plain object, such as a spread {...user} or a raw row, or one that writes through @Res(), escapes @Exclude(), so the password leaks.
As a lead on a NestJS 12 codebase, would you standardise response shaping on ClassSerializerInterceptor or the new StandardSchemaSerializerInterceptor, and why?
basics
~20 sBoth read @SerializeOptions(). ClassSerializerInterceptor applies class-transformer decorators to class instances, a denylist by default; Nest 12's StandardSchemaSerializerInterceptor runs each response through a schema, and a mismatch is a 500. Choose by where the team's types already live.
In NestJS 12, what response does the built-in exception filter send when a handler throws a NotFoundException, and when it throws a plain Error?
basics
~20 sNest's built-in global filter turns any HttpException, such as NotFoundException, into a JSON body with its status and message, here a 404. A plain Error outside that hierarchy becomes a logged 500 whose message is "Internal server error".
In a NestJS 12 app, how do you bind a class middleware to some routes with MiddlewareConsumer, and when is functional middleware enough?
basics
~10 sMake the module implement NestModule and, in configure(consumer), call consumer.apply(TenantMiddleware).forRoutes(OrdersController), optionally with exclude() first. A plain function is enough when the middleware needs no injected dependencies.
In NestJS 12, how do you write an exception filter with @Catch and ArgumentsHost that turns a domain NotFoundError into a 404 response?
basics
~10 sWrite a class implementing ExceptionFilter, decorate it @Catch(NotFoundError), and in catch(exception, host) call host.switchToHttp().getResponse() to send a 404 yourself. Bind it with @UseFilters on a handler or controller, or globally.
In NestJS 12, how does registering a global exception filter with APP_FILTER differ from app.useGlobalFilters(), and when do you extend BaseExceptionFilter?
basics
~20 sapp.useGlobalFilters(new X()) builds the filter outside any module, so it gets no injected dependencies; an APP_FILTER provider is global too but Nest creates it with injection. Extend BaseExceptionFilter to add behaviour and still delegate to Nest's default response.
In a NestJS 12 app, a tenant middleware throws UnauthorizedException, but the controller's @UseFilters filter never formats it. Why, and what fixes it?
basics
~20 sConsumer-bound middleware runs before Nest has selected a route handler, so only global exception filters apply to its errors; controller-scoped and method-scoped filters are never consulted. Register the formatting filter globally, through APP_FILTER or app.useGlobalFilters().
In a NestJS 12 app, in what order do middleware, guards, interceptors, pipes, the handler and exception filters run for one request?
basics
~10 sMiddleware runs first, then guards, then the interceptors' before-phase, then pipes, then the route handler; interceptors then unwind in reverse, and exception filters run only when something along the way throws uncaught.
In a NestJS 12 app, how do global, controller and route bindings order guards and interceptors, and why do interceptors unwind in reverse?
basics
~10 sGuards and interceptors both run global, then controller, then route, and in listed order inside one decorator. Each interceptor wraps the next one's Observable, so their after-phase unwinds route, controller, then global.
In a NestJS 12 handler whose parameters carry pipes, in what order do global, controller, route and parameter pipes run?
basics
~20 sEach argument passes through global pipes, then controller and route @UsePipes() pipes, then its own parameter pipes. Across arguments Nest starts with the last parameter and ends with the first, and calls the handler only once every argument resolves.
In a NestJS 12 app with route, controller and global exception filters, which one handles a thrown exception, and why does the closest filter not always win?
basics
~20 sNest checks route filters, then controller filters, then global ones, and the first whose @Catch() matches the exception, or is empty, handles it alone. A closer filter wins only when its @Catch() matches, and no filter hands the exception on.
In a NestJS 12 app, a guard registered through APP_GUARD and one passed to app.useGlobalGuards() are both global; which runs first, and why?
basics
~10 sA singleton APP_GUARD guard runs first: Nest adds APP_GUARD providers while NestFactory.create() builds the module graph, and app.useGlobalGuards() later appends. A request-scoped APP_GUARD guard runs after all singleton global guards instead.
In NestJS, which lifecycle hook methods can a provider implement, and in what order does Nest call them from boot to shutdown?
basics
~10 sNestJS calls onModuleInit, then onApplicationBootstrap when the app initializes, and onModuleDestroy, beforeApplicationShutdown and onApplicationShutdown, in that order, when app.close() runs or an opted-in shutdown signal arrives.
A NestJS 12 service runs onModuleDestroy on app.close() in tests, but never when the orchestrator stops its pod with SIGTERM; why?
basics
~20 sNestJS only listens for process signals after app.enableShutdownHooks() is called at bootstrap. Without it, SIGTERM takes Node's default action and the process dies before any shutdown hook runs; tests pass because they call app.close() directly.
In NestJS, should a boot-time cache warm-up go in onModuleInit or onApplicationBootstrap, and when do app.init() and app.listen() run them?
basics
~10 sPut it in onApplicationBootstrap when it needs other modules ready, because NestJS finishes every module's onModuleInit first. Both hooks run during app.init(), which app.listen() calls if needed, and are awaited before the port opens.
In a NestJS app, should a message-broker connection be closed in onModuleDestroy, beforeApplicationShutdown or onApplicationShutdown, and why?
basics
~20 sClose it in onApplicationShutdown when requests may still use it: NestJS calls that hook only after closing the HTTP server. Use onModuleDestroy or beforeApplicationShutdown to stop taking new work while the server is still open.
After upgrading to NestJS 12, two dependent providers in one module run onModuleInit in a different order; how does Nest 12 order lifecycle hooks?
basics
~20 sNestJS 12 orders hooks by module, deepest and global modules first and the root last, then by hierarchy level inside each module, so a provider's onModuleInit runs after those it constructor-injects. Shutdown hooks walk the same order backwards.
In NestJS, how do you unit-test an OrdersService with Test.createTestingModule() and a fake repository?
basics
~10 sTest.createTestingModule() takes the same metadata as @Module() and returns a builder; awaiting compile() wires a real Nest container. Register OrdersService plus { provide: OrdersRepository, useValue: fake }, then read the service with moduleRef.get(OrdersService).
In a NestJS e2e test, what do createNestApplication(), app.init(), getHttpServer() and app.close() each contribute to a Supertest request?
basics
~20 screateNestApplication() wraps the compiled TestingModule in an INestApplication on the Express adapter; app.init() registers middleware and routes and runs init hooks; getHttpServer() gives Supertest the Node server; app.close() runs shutdown hooks and closes the server.
In a NestJS TestingModuleBuilder, how do overrideProvider, overrideGuard and overrideModule differ, and what can each be replaced with?
basics
~20 soverrideProvider swaps a registered provider; overrideGuard (like overrideInterceptor, overrideFilter, overridePipe) swaps an enhancer bound by decorator. Both take useValue, useClass or useFactory({ factory, inject }); overrideModule takes useModule. An override whose token matches nothing is silently ignored.
In a NestJS TestingModule, why does get() throw for a request-scoped provider, and how do resolve() and a context ID help?
basics
~20 sget() returns only static singletons, so a request-scoped or transient provider, or anything depending on one, throws InvalidClassScopeException. resolve() builds the instance in a DI sub-tree; each call gets a new one unless you pass the same contextId.
In a NestJS e2e test, why does overrideGuard(AppAuthGuard) leave orders requests failing with 403 when that guard is registered through APP_GUARD, and how do you fix it?
basics
~10 s{ provide: APP_GUARD, useClass: AppAuthGuard } is stored under a generated APP_GUARD token, so no override keyed by AppAuthGuard matches. Register AppAuthGuard as a provider, point APP_GUARD at it with useExisting, then call overrideProvider(AppAuthGuard).
In a NestJS app, how do you restrict a route to certain roles with a custom @Roles() decorator and a roles guard?
basics
~20 sCreate a Roles decorator with Reflector.createDecorator() or SetMetadata(), put it on the handler, and write a CanActivate guard that reads it through Reflector and compares it with request.user's roles; a false return makes Nest answer 403.
In a NestJS app using @nestjs/passport, what should a PassportStrategy subclass's validate() return, and where does that value end up?
basics
~10 svalidate() should return the authenticated user, which AuthGuard assigns to req.user before the handler runs. Returning null or false fails authentication with a 401; a thrown exception goes to Nest's exception layer instead.
In a NestJS 12 app, why must the authentication guard run before a roles or policy guard, and what decides which global guard runs first?
basics
~20 sRole and policy guards read the user that authentication puts on request.user, so run first they see nobody. Global guards precede controller and route guards; singleton APP_GUARD providers run in module-scan order, before app.useGlobalGuards() ones.
In a NestJS app, how do you register a JwtAuthGuard extending AuthGuard('jwt') globally and still let routes marked @Public() through?
basics
~10 sProvide the guard under the APP_GUARD token, mark open routes with a @Public() decorator built on SetMetadata, and override canActivate() to read that flag with Reflector, returning true before calling super.canActivate().
In a NestJS 12 app importing AuthenticationModule from @nestjs/authentication, why does a new health-check route answer 401, and how do you open it?
basics
~20 sAuthenticationModule.forRoot() registers AuthenticationGuard as a global guard by default, so every route needs a signed-in user and anonymous calls get 401. Marking the health route @Public() makes the guard skip it: no credential provider runs.
In a NestJS 12 microservice, what is the difference between a @MessagePattern() handler and an @EventPattern() handler?
basics
~10 sA @MessagePattern() handler serves request-response: its return value goes back to whoever called ClientProxy.send(). An @EventPattern() handler serves fire-and-forget events from emit(): nothing is returned, and several handlers may share one pattern.
In a NestJS 12 order service, why does ClientProxy.send() deliver nothing until subscribed, while emit() publishes immediately?
basics
~10 sClientProxy.send() returns a cold Observable: the request is published only when something subscribes, and again for each subscription. emit() returns a hot Observable that dispatches the event immediately, whether or not anyone subscribes.
A NestJS 12 hybrid app's global ValidationPipe and auth guard work on HTTP routes but never run for its message handlers. Why, and what fixes it?
basics
~20 sconnectMicroservice() gives each connected listener its own empty config, so useGlobal*() enhancers and APP_GUARD or APP_PIPE providers stay HTTP-only. Pass { inheritAppConfig: true } as its second argument, after the useGlobal*() calls, to share them.
In a NestJS 12 microservice, why does a NotFoundException thrown in a @MessagePattern() handler reach the caller as 'Internal server error'?
basics
~10 sMessage handlers are served by Nest's base RPC exception filter, which only understands RpcException. Any other error, NotFoundException included, is replaced by { status: 'error', message: 'Internal server error' }. Throw RpcException instead.
In NestJS 12, what must change when an order service's microservice transport moves from TCP to NATS or Kafka?
basics
~20 sThe transport and options objects change on both sides: createMicroservice() or connectMicroservice() on the consumer, ClientsModule on the producer, plus the transporter's driver package. Handlers and patterns mostly stay; @Ctx() types and quirks such as Kafka reply topics change.