skip to content

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 pageshow

explore

questions

69 · 11 sections

In a NestJS 12 app, why can OrdersService not inject PaymentsService from PaymentsModule until that module exports it?

level: juniorimportance: must knowfreq 80%
basics
~10 s

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

open as a page

In NestJS, how do useClass, useValue, useFactory and useExisting providers differ, and when must a consumer use @Inject() with a token?

level: middleimportance: must knowfreq 65%
basics
~20 s

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

open as a page

In NestJS, what is a dynamic module returned by forRoot() or register(), and what does ConfigurableModuleBuilder generate for you?

level: middleimportance: should knowfreq 40%
basics
~20 s

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

open as a page

In a NestJS app, OrdersService and PaymentsService inject each other and bootstrap fails. What does Nest report, and how does forwardRef() resolve it?

level: seniorimportance: should knowfreq 50%
basics
~20 s

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

open as a page

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?

level: seniorimportance: should knowfreq 45%
basics
~20 s

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

open as a page

In a NestJS 12 app, what does ConfigModule.forRoot() do with a .env file, and how do other modules get ConfigService?

level: juniorimportance: must knowfreq 65%
basics
~20 s

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

open as a page

In NestJS 12, how does ConfigModule.forRoot's validationSchema stop the app booting on a missing secret, and what does ConfigService then return?

level: middleimportance: must knowfreq 55%
basics
~20 s

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

open as a page

In NestJS's @nestjs/config, how do ConfigService.get and ConfigService.getOrThrow differ, and when does each return undefined or throw?

level: middleimportance: should knowfreq 50%
basics
~10 s

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

open as a page

In NestJS's @nestjs/config, what does registerAs() create, and how do you inject a namespace with ConfigType instead of ConfigService.get?

level: middleimportance: should knowfreq 40%
basics
~10 s

registerAs('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'.

open as a page

In a NestJS app, MailModule imports ConfigModule.forFeature(mailConfig), yet another module's constructor reads configService.get('mail.host') and gets undefined; why?

level: seniorimportance: should knowfreq 30%
basics
~20 s

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

open as a page

In a NestJS controller, how do @Controller, @Get, @Post, @Param, @Query and @Body turn an HTTP request into a handler call?

level: juniorimportance: must knowfreq 70%
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.

open as a page

In NestJS, what changes when a route handler injects the response with @Res(), and when do you need @Res({ passthrough: true })?

level: middleimportance: should knowfreq 45%
basics
~20 s

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

open as a page

In NestJS, how does app.enableVersioning() with VersioningType URI, HEADER or MEDIA_TYPE route a request to a @Version('1') or @Version('2') handler?

level: middleimportance: should knowfreq 25%
basics
~20 s

enableVersioning() 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.

open as a page

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?

level: seniorimportance: should knowfreq 35%
basics
~10 s

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

open as a page

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?

level: middleimportance: nice to knowfreq 12%
basics
~10 s

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

open as a page

In NestJS, what is a pipe, what does its transform() method receive, and what happens when it throws?

level: juniorimportance: must knowfreq 70%
basics
~20 s

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

open as a page

In NestJS 12, what do ValidationPipe's whitelist, forbidNonWhitelisted and transform options do to a create-order request body?

level: middleimportance: must knowfreq 70%
basics
~20 s

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

open as a page

In NestJS, how do ParseIntPipe and DefaultValuePipe handle a page query parameter that is missing, empty or non-numeric?

level: middleimportance: should knowfreq 45%
basics
~20 s

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

open as a page

In NestJS 12, how does StandardSchemaValidationPipe validate @Body({ schema }), and what happens if the pipe is never registered?

level: middleimportance: should knowfreq 35%
basics
~20 s

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

open as a page

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?

level: seniorimportance: should knowfreq 40%
basics
~20 s

ValidationPipe 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 }).

open as a page

In a NestJS 12 app, what does a guard's canActivate() receive and return, and what happens when it denies a request?

level: juniorimportance: must knowfreq 70%
basics
~20 s

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

open as a page

In a NestJS 12 interceptor, what does CallHandler.handle() return, and how do you time or reshape a handler's result with RxJS?

level: middleimportance: must knowfreq 62%
basics
~20 s

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

open as a page

In NestJS 12, how does a guard read metadata from a Reflector.createDecorator decorator, and when do getAllAndOverride and getAllAndMerge differ?

level: middleimportance: should knowfreq 50%
basics
~10 s

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

open as a page

A NestJS 12 app binds ClassSerializerInterceptor globally and marks UserEntity.password with @Exclude(), yet one endpoint still returns the password; why?

level: seniorimportance: should knowfreq 38%
basics
~20 s

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

open as a page

As a lead on a NestJS 12 codebase, would you standardise response shaping on ClassSerializerInterceptor or the new StandardSchemaSerializerInterceptor, and why?

level: principalimportance: nice to knowfreq 18%
basics
~20 s

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

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Nest'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".

open as a page

In a NestJS 12 app, how do you bind a class middleware to some routes with MiddlewareConsumer, and when is functional middleware enough?

level: juniorimportance: must knowfreq 58%
basics
~10 s

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

open as a page

In NestJS 12, how do you write an exception filter with @Catch and ArgumentsHost that turns a domain NotFoundError into a 404 response?

level: middleimportance: must knowfreq 60%
basics
~10 s

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

open as a page

In NestJS 12, how does registering a global exception filter with APP_FILTER differ from app.useGlobalFilters(), and when do you extend BaseExceptionFilter?

level: middleimportance: should knowfreq 45%
basics
~20 s

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

open as a page

In a NestJS 12 app, a tenant middleware throws UnauthorizedException, but the controller's @UseFilters filter never formats it. Why, and what fixes it?

level: seniorimportance: should knowfreq 40%
basics
~20 s

Consumer-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().

open as a page

In a NestJS 12 app, in what order do middleware, guards, interceptors, pipes, the handler and exception filters run for one request?

level: juniorimportance: must knowfreq 76%
basics
~10 s

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

open as a page

In a NestJS 12 app, how do global, controller and route bindings order guards and interceptors, and why do interceptors unwind in reverse?

level: middleimportance: should knowfreq 58%
basics
~10 s

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

open as a page

In a NestJS 12 handler whose parameters carry pipes, in what order do global, controller, route and parameter pipes run?

level: middleimportance: should knowfreq 38%
basics
~20 s

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

open as a page

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?

level: seniorimportance: should knowfreq 45%
basics
~20 s

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

open as a page

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?

level: seniorimportance: nice to knowfreq 28%
basics
~10 s

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

open as a page

In NestJS, which lifecycle hook methods can a provider implement, and in what order does Nest call them from boot to shutdown?

level: juniorimportance: must knowfreq 60%
basics
~10 s

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

open as a page

A NestJS 12 service runs onModuleDestroy on app.close() in tests, but never when the orchestrator stops its pod with SIGTERM; why?

level: seniorimportance: must knowfreq 50%
basics
~20 s

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

open as a page

In NestJS, should a boot-time cache warm-up go in onModuleInit or onApplicationBootstrap, and when do app.init() and app.listen() run them?

level: middleimportance: should knowfreq 45%
basics
~10 s

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

open as a page

In a NestJS app, should a message-broker connection be closed in onModuleDestroy, beforeApplicationShutdown or onApplicationShutdown, and why?

level: middleimportance: should knowfreq 40%
basics
~20 s

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

open as a page

After upgrading to NestJS 12, two dependent providers in one module run onModuleInit in a different order; how does Nest 12 order lifecycle hooks?

level: seniorimportance: should knowfreq 25%
basics
~20 s

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

open as a page

In NestJS, how do you unit-test an OrdersService with Test.createTestingModule() and a fake repository?

level: juniorimportance: must knowfreq 62%
basics
~10 s

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

open as a page

In a NestJS e2e test, what do createNestApplication(), app.init(), getHttpServer() and app.close() each contribute to a Supertest request?

level: middleimportance: must knowfreq 58%
basics
~20 s

createNestApplication() 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.

open as a page

In a NestJS TestingModuleBuilder, how do overrideProvider, overrideGuard and overrideModule differ, and what can each be replaced with?

level: middleimportance: must knowfreq 55%
basics
~20 s

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

open as a page

In a NestJS TestingModule, why does get() throw for a request-scoped provider, and how do resolve() and a context ID help?

level: middleimportance: should knowfreq 30%
basics
~20 s

get() 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.

open as a page

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?

level: seniorimportance: should knowfreq 38%
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).

open as a page

In a NestJS app, how do you restrict a route to certain roles with a custom @Roles() decorator and a roles guard?

level: juniorimportance: must knowfreq 65%
basics
~20 s

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

open as a page

In a NestJS app using @nestjs/passport, what should a PassportStrategy subclass's validate() return, and where does that value end up?

level: juniorimportance: must knowfreq 70%
basics
~10 s

validate() 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.

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~20 s

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

open as a page

In a NestJS app, how do you register a JwtAuthGuard extending AuthGuard('jwt') globally and still let routes marked @Public() through?

level: middleimportance: must knowfreq 62%
basics
~10 s

Provide 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().

open as a page

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?

level: juniorimportance: should knowfreq 30%
basics
~20 s

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

open as a page

In a NestJS 12 microservice, what is the difference between a @MessagePattern() handler and an @EventPattern() handler?

level: juniorimportance: should knowfreq 30%
basics
~10 s

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

open as a page

In a NestJS 12 order service, why does ClientProxy.send() deliver nothing until subscribed, while emit() publishes immediately?

level: middleimportance: should knowfreq 35%
basics
~10 s

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

open as a page

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?

level: seniorimportance: should knowfreq 25%
basics
~20 s

connectMicroservice() 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.

open as a page

In a NestJS 12 microservice, why does a NotFoundException thrown in a @MessagePattern() handler reach the caller as 'Internal server error'?

level: seniorimportance: should knowfreq 25%
basics
~10 s

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

open as a page

In NestJS 12, what must change when an order service's microservice transport moves from TCP to NATS or Kafka?

level: middleimportance: nice to knowfreq 20%
basics
~20 s

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

open as a page