Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 42 ยท Practice and Review

NestJS Interview Questions

25 NestJS interview questions with short answers: DI, lifecycle, request pipeline order, scopes, guards vs middleware, microservices and testing, plus live demos.

NestJS interviews usually mix three kinds of questions: vocabulary ("what is a provider?"), mechanics ("in what order do guards and pipes run?") and judgment ("when would you avoid request-scoped providers?"). This page collects 25 common ones, grouped by level: Junior, Mid and Senior.

Each answer is hidden. Say your answer out loud first, then open it and compare. After the lists you will find two runnable demos, a request-pipeline tracer and a provider-scope counter. They are hand-written stand-ins in plain JavaScript that reproduce the behavior; the real framework needs Node and npm, so Nest's own code stays read-only in this track.

A strong answer gives a one-sentence definition, a concrete example or consequence, and a trade-off. "Request scope gives each request its own instance, but every dependent provider becomes request-scoped too, which costs performance" beats "request scope is per request".

What interviewers look for

Vocabulary Module, provider, controller.
Mechanics Order, lifecycle, scopes.
Judgment Trade-offs and when to avoid things.
1 / 2

Junior level

1. What is NestJS?

A TypeScript-first Node.js framework that adds structure on top of an HTTP library. It organizes code into modules, controllers and providers, uses dependency injection and decorators, and by default runs on Express (Fastify is available through an adapter). It gives large teams one shared architecture instead of each project inventing its own. See What is NestJS?.

2. What are modules, controllers and providers?

A module groups related code and declares what it imports, provides and exports. A controller receives requests and maps routes to methods. A provider is any injectable class (services, repositories, factories) that holds logic and is created by the Nest container. Controllers should stay thin and call providers. See Modules.

3. What is dependency injection, and why does Nest use it?

A class declares what it needs in its constructor and the container supplies it, instead of the class creating its own dependencies. Benefits: one place wires the app, instances are shared where appropriate, and tests can substitute fakes without touching the class under test. See Providers and Dependency Injection.

4. What does @Injectable() do?

It marks a class as managed by the container and, because it is a decorator, makes TypeScript emit the constructor parameter types as metadata. Nest reads that metadata to know which providers to pass in. The decorator alone does not register the class: it must also appear in a module's providers array.

5. What status codes do routes return by default?

200 for most methods and 201 for @Post(). Change it with @HttpCode(204). Thrown HttpException subclasses carry their own status, and an unknown thrown error becomes 500. See Controllers and Routing.

6. How do you read route parameters, the query string and the body?

With parameter decorators: @Param('id'), @Query('limit'), @Body(), plus @Headers() and @Req(). Values arrive as strings unless a pipe (or a DTO with transformation enabled) converts them. See Reading Request Data.

7. What is a DTO, and how is it validated?

A DTO (data transfer object) is a class that describes the shape of incoming data. With class-validator decorators on its fields and a ValidationPipe, invalid bodies are rejected with 400 before the handler runs. Options such as whitelist: true strip unknown properties and transform: true converts plain objects into DTO instances. See Pipes and Validation.

8. What is the difference between Express and Nest?

Express is a small routing and middleware library with no opinion about structure. Nest uses Express (or Fastify) underneath and adds modules, DI, decorators, a request pipeline (guards, pipes, interceptors, filters) and conventions for testing and microservices. Compare with Express.

Mid level

9. In what order does a request travel through Nest?

Middleware, then guards, then interceptors (the "before" part), then pipes, then the route handler. On the way back the interceptors' "after" parts run in reverse order. If anything throws, exception filters turn the error into a response. For guards, interceptors and pipes, global ones run before controller-level ones, which run before route-level ones. The first demo below prints this order.

10. What is the difference between a guard and middleware?

Both can stop a request. Middleware runs first and only sees the raw request and response; it does not know which handler will run. A guard gets an ExecutionContext, so it knows the target class and method and can read metadata such as @Roles('admin'). Use middleware for generic request preparation (logging, cookies, correlation ids) and guards for access decisions. See Middleware and Guards.

11. Pipe, guard, interceptor, filter: what does each one do?

A guard decides whether the request may proceed. A pipe validates or transforms handler arguments. An interceptor wraps the handler and can map the result, time it, cache it or add a timeout. A filter catches exceptions and shapes the error response. One question per tool: may it run, are the inputs valid, what happens around it, what if it fails.

12. What are the provider scopes?

DEFAULT is a singleton shared by the whole app. REQUEST creates a new instance per incoming request. TRANSIENT creates a new instance for every consumer that injects it. Scope bubbles up: anything that depends on a request-scoped provider becomes request-scoped too. See Dynamic Modules and Provider Scopes. The second demo counts instances.

13. Why avoid request-scoped providers when you can?

Each request builds a new object graph for every affected class, which costs CPU and memory, and the bubbling means one request-scoped dependency can make a whole controller chain request-scoped. Prefer passing request data as method arguments, or use AsyncLocalStorage-based request context, and keep providers as singletons.

14. What lifecycle hooks exist, and in what order do they run?

At startup: onModuleInit, then onApplicationBootstrap. At shutdown: onModuleDestroy, then beforeApplicationShutdown, then onApplicationShutdown. The shutdown hooks only react to process signals if you call app.enableShutdownHooks() (or when you call app.close()). Do not rely on the order between different providers' hooks. See Deployment and Performance.

15. What forms can a custom provider take?

useClass (instantiate a class, often a different one in tests), useValue (a ready object), useFactory (a function that may be async and may inject other providers) and useExisting (an alias to another token). The token can be a class, a string or a Symbol, and string/symbol tokens are injected with @Inject(token). See Custom Providers.

16. What is a dynamic module?

A module whose description is built at import time by a static method such as forRoot(options) or forRootAsync({...}). It lets the importer configure the module and is how ConfigModule, TypeOrmModule and JwtModule accept settings. See Dynamic Modules and Provider Scopes.

17. How do you deal with a circular dependency?

First, treat it as a design smell and extract the shared part into a third provider. If you must keep it, use forwardRef(() => OtherService) with @Inject() on both sides (and the same for modules). Without it Nest fails at startup with an error about a dependency it cannot resolve (circular file imports can also leave a class undefined when the decorator metadata is read).

18. How do exception filters work?

Throwing an HttpException (or a subclass such as NotFoundException) produces a response with its status. A class decorated with @Catch(SomeError) that implements ExceptionFilter can turn that error into any response shape. Filters can be bound to a route, a controller or globally, and the most specific matching one wins. Unknown errors become a generic 500. See Exception Filters and Errors.

19. What goes wrong if you inject @Res() into a handler?

Nest then assumes you will send the response yourself, so returning a value no longer sends it, and features that post-process the response (interceptors that map the result, @HttpCode) stop working as expected. Use @Res({ passthrough: true }) when you only need to set a header or cookie and still want Nest to send the returned value.

20. When do you make a module global?

With @Global() (or global: true on a dynamic module) its exports are available everywhere without importing it. That suits true cross-cutting services such as configuration. Overuse hides dependencies, so most feature modules should stay explicit about what they import.

Senior level

21. How do you test a Nest service and a whole endpoint?

Unit tests build a testing module with Test.createTestingModule({ providers: [...] }), replace collaborators with overrideProvider(X).useValue(fake) or by providing a fake directly, and call the service. End-to-end tests create the real app from AppModule (overriding the database or external clients), call app.init() and drive it with supertest against app.getHttpServer(). Keep unit tests fast and focused, and use a real or containerized database for the few tests that need one. See Testing Nest Applications.

22. Message patterns versus event patterns in microservices?

A @MessagePattern() handler implements request-response: the caller waits for a reply. An @EventPattern() handler is fire-and-forget: there is no reply and no caller waiting. Pick events for notifications ("order created") and messages when you need an answer. Transports include TCP, Redis, NATS, RabbitMQ, Kafka and gRPC, and a hybrid app can serve HTTP and a microservice transport at once. See Microservices and Transports.

23. How do you scale a WebSocket gateway to several instances?

Rooms and connections live in one process's memory, so a message emitted on instance A does not reach clients connected to instance B. Use an adapter that relays events between instances (for example the Socket.IO Redis adapter), and keep per-user state in a shared store. Sticky sessions may also be required for some transports. See WebSockets and Gateways.

24. How would you make a Nest API faster?

Measure first. Common wins: keep providers as singletons, switch to the Fastify adapter if the platform fits, cache hot reads, avoid N+1 queries, paginate lists, compress responses (often at the proxy), and move slow work into queues. See Deployment and Performance and Caching, Throttling and Scheduling.

25. What would be on your security checklist for a Nest app?

Validation with whitelist: true and forbidNonWhitelisted to block mass assignment, authentication on every route by default (global guard plus @Public()), authorization checks per resource, helmet, a strict CORS origin list, rate limiting, secrets only from the environment, hashed passwords, and regular dependency updates. See Security and Hardening.

Demo 1: trace the request pipeline

Predict the line of output before you press Run. The stand-in builds a global, a controller and a route binding for guards, interceptors and pipes, and records every step. It mirrors the documented order; it is not Nest's implementation.

JS Request pipeline tracer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your prediction against the list. Notice that the interceptors' "after" steps appear in reverse order (route first, global last) and that on failure they still run before the exception filter does.

Demo 2: count instances per scope

How many times is each class constructed after startup and three requests? Work it out first. The stand-in applies the rules from question 12: singletons are created once, request scope creates one instance per request, transient creates one per consumer, and a singleton that depends on a request-scoped provider is itself treated as request-scoped.

JS Provider scopes and instance counts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

UsersController declared nothing special, yet it is rebuilt for every request because it depends on AuditService, which depends on the request-scoped RequestContext. Logger is created once for UsersService at startup and again for every AuditService, because each consumer gets its own transient copy. That is why interviewers ask about scope bubbling.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which sequence matches Nest's request pipeline?

    Middleware runs first, then guards, then the interceptors' before-part, then pipes, then the handler.
  2. 2. What is the main reason a guard can do things middleware cannot?

    Knowing which handler will run lets a guard read metadata like roles. Middleware only sees the raw request.
  3. 3. A singleton ReportService injects a request-scoped RequestContext. What happens to ReportService?

    Request scope bubbles up the dependency chain, so every dependent is created per request.
  4. 4. You inject @Res() and return an object from the handler. What is the typical result?

    With @Res() Nest no longer sends the returned value. Use passthrough: true to keep the normal behavior.
  5. 5. Which handler decorator expects no reply to the sender in a microservice?

    Event patterns are fire-and-forget. Message patterns are request-response.

Summary

  • Know the vocabulary: modules group, controllers route, providers hold logic, and the container wires them with DI.
  • Memorize the order: middleware, guards, interceptors, pipes, handler, with filters catching errors.
  • Scopes: DEFAULT is a singleton, REQUEST is per request and bubbles up, TRANSIENT is per consumer.
  • Lifecycle: onModuleInit, onApplicationBootstrap, then the destroy and shutdown hooks (which need shutdown hooks enabled).
  • For senior questions talk about trade-offs: testing strategy, message versus event patterns, scaling gateways, performance and security.

Finish the track with the NestJS Cheat Sheet.