NestJS Middle cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. In what order do Nest's request-processing layers run?

    Correct answer: Middleware → guards → interceptors → pipes → handler

    Within each layer, global ones run first, then controller-level, then route-level. Exception filters handle errors thrown anywhere along the way.

  2. 2. Why should authentication be a guard rather than middleware?

    Correct answer: Guards know the handler and its metadata

    Middleware doesn't know which route handler will run. Guards are designed for 'may this request proceed?' decisions.

  3. 3. What is ExecutionContext used for?

    Correct answer: Reading the current handler, class and request

    context.switchToHttp().getRequest(), context.getHandler(), context.getClass() and context.getType() are the common calls.

  4. 4. How does a roles guard read roles declared on a route?

    export const Roles = Reflector.createDecorator<string[]>();
    
    @Roles(["admin"])
    @Delete(":id")
    remove() {}

    Correct answer: It reads route metadata through Reflector

    getAllAndOverride lets a method-level value override a class-level one; getAllAndMerge combines them.

  5. 5. How do you register a global guard that can inject other providers?

    providers: [{ provide: APP_GUARD, useClass: JwtAuthGuard }]

    Correct answer: With the APP_GUARD token in a module's providers

    app.useGlobalGuards() takes an instance created outside the DI container, so its dependencies aren't injected. APP_PIPE, APP_INTERCEPTOR and APP_FILTER work the same way.

  6. 6. What does an interceptor's intercept(context, next) return?

    intercept(context: ExecutionContext, next: CallHandler) {
      const start = Date.now();
      return next.handle().pipe(tap(() => console.log(Date.now() - start)));
    }

    Correct answer: An Observable of the handler's result

    If you don't call next.handle(), the handler never runs. That's how caching interceptors return stored responses.

  7. 7. How can an interceptor wrap every response in { data: ... }?

    Correct answer: next.handle().pipe(map((data) => ({ data })))

    Interceptors are the place for cross-cutting response changes. Be consistent: errors are shaped by exception filters, not interceptors.

  8. 8. How can an interceptor add a timeout to slow handlers?

    Correct answer: With the RxJS timeout operator on next.handle()

    This stops waiting for the result, but the underlying work keeps running unless you also cancel it (for example with an AbortSignal).

  9. 9. How do you write a custom parameter decorator like @User()?

    export const User = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
      return ctx.switchToHttp().getRequest().user;
    });

    Correct answer: With the createParamDecorator function

    Custom decorators can also accept data (@User('email')) and be combined with pipes, e.g. @User(new ValidationPipe()).

  10. 10. How do you combine several decorators into one, e.g. guards plus Swagger annotations?

    Correct answer: With the applyDecorators(...) helper

    A single @Auth('admin') decorator can set roles metadata, apply guards and document the route.

  11. 11. When would you use useFactory for a provider?

    {
      provide: "REDIS",
      useFactory: async (config: ConfigService) => createClient({ url: config.get("REDIS_URL") }).connect(),
      inject: [ConfigService],
    }

    Correct answer: When creating the instance needs logic or dependencies

    Async factories delay app startup until they resolve, so the connection is ready before anything uses it.

  12. 12. What is useExisting for?

    Correct answer: An alias token for an existing provider instance

    For example, expose a LoggerService interface token that points to an existing PinoLogger instance.

  13. 13. Why inject an interface-like dependency by token instead of by class?

    @Inject(PAYMENT_GATEWAY) private readonly payments: PaymentGateway

    Correct answer: TypeScript interfaces don't exist at runtime

    Register { provide: PAYMENT_GATEWAY, useClass: StripeGateway } in production and a fake in tests.

  14. 14. What is a dynamic module?

    Correct answer: A module configured at runtime via a static method

    ConfigModule.forRoot(), TypeOrmModule.forFeature() and JwtModule.register() are dynamic modules. ConfigurableModuleBuilder helps write your own.

  15. 15. What's the usual convention for forRoot, register and forFeature?

    Correct answer: forRoot once, register per module, forFeature for parts

    It's a convention, not a rule, but following it makes modules predictable for other developers.

  16. 16. What are the three injection scopes in Nest?

    Correct answer: DEFAULT, REQUEST and TRANSIENT

    REQUEST creates an instance per request; TRANSIENT gives each consumer its own instance.

  17. 17. What is a side effect of making a provider request-scoped?

    Correct answer: Everything depending on it becomes request-scoped too

    Scope bubbles up the injection chain. For per-request data like a request ID, AsyncLocalStorage (e.g. via nestjs-cls) is often a cheaper option.

  18. 18. How do you resolve a circular dependency between two providers?

    Correct answer: Refactor, or use forwardRef() on both sides

    Cycles usually mean responsibilities are mixed. Extracting the shared logic into a third provider is the cleaner fix.

  19. 19. What does ModuleRef let you do?

    Correct answer: Get provider instances dynamically

    It's useful for strategy patterns where the implementation is chosen at runtime. Prefer normal constructor injection when possible.

  20. 20. Which lifecycle hook is the right place to open a connection that other modules rely on during startup?

    Correct answer: onModuleInit or an async factory

    Constructors can't be async. Nest awaits async onModuleInit hooks before calling onApplicationBootstrap.

  21. 21. How do you validate nested objects in a DTO?

    export class CreateOrderDto {
      @ValidateNested({ each: true })
      @Type(() => OrderItemDto)
      items: OrderItemDto[];
    }

    Correct answer: @ValidateNested() together with @Type()

    Without @Type, the nested values stay plain objects and their decorators are ignored.

  22. 22. What is a risk of using database entities directly as request DTOs?

    Correct answer: Clients can set fields they shouldn't (mass assignment)

    Separate input DTOs list only the allowed fields. Response DTOs control what leaves the API.

  23. 23. How can a custom validation rule check something asynchronous, like 'email is not taken'?

    Correct answer: With a custom class-validator constraint class

    Async checks improve error messages but have race conditions. The database constraint must catch concurrent duplicates.

  24. 24. Why might you write a custom pipe instead of using ValidationPipe?

    Correct answer: For specific transforms, like an ID to a loaded entity

    A pipe implements transform(value, metadata). Zod-based pipes are popular when schemas are shared with the front end.

  25. 25. What does @Expose({ groups: ['admin'] }) with ClassSerializerInterceptor allow?

    Correct answer: Showing fields only for a given serialization group

    Set the groups per route with @SerializeOptions({ groups: [...] }).

  26. 26. How do you write a global filter that formats all errors as RFC 9457 problem details?

    Correct answer: A @Catch() class registered with APP_FILTER

    Map HttpExceptions to their status, unknown errors to 500 with a generic message, and log the real error with a request ID.

  27. 27. Where should database errors like unique violations be translated into HTTP errors?

    Correct answer: In one dedicated place, mapping them to a 409

    Never leak SQL or stack traces. A filter for ORM errors keeps the mapping in one place.

  28. 28. Why can exception filters behave differently in microservices and HTTP?

    Correct answer: Each transport has its own context

    ArgumentsHost.getType() tells you the transport, so one filter can handle several types if needed.

  29. 29. How does Passport fit into Nest authentication?

    Correct answer: @nestjs/passport wraps strategies as guards

    A strategy class extends PassportStrategy(Strategy) and implements validate(), whose return value becomes request.user.

  30. 30. How do you implement permission rules more fine-grained than roles, e.g. 'users can edit only their own posts'?

    Correct answer: With policy-based authorization, e.g. CASL

    Ownership checks often need the loaded resource, so they usually live in the service after fetching it.

  31. 31. Why check object ownership in addition to authentication?

    Correct answer: Otherwise a changed ID exposes others' data

    Broken Object Level Authorization is the top item in the OWASP API Security Top 10.

  32. 32. How do you run several TypeORM operations in one transaction in Nest?

    Correct answer: dataSource.transaction(async (manager) => ...)

    Operations through injected repositories outside the manager don't join the transaction. Libraries like typeorm-transactional use ALS to propagate it.

  33. 33. Why is synchronize: true in TypeORM dangerous in production?

    Correct answer: It alters the schema on startup and can drop data

    Use migrations in production. synchronize is only convenient for local prototypes.

  34. 34. What's a clean way to keep Prisma or TypeORM details out of business logic?

    Correct answer: Put data access behind repository providers

    This adds a layer, so it pays off in larger domains or when you need to swap storage or test without a database.

  35. 35. How do you cache GET responses in Nest?

    Correct answer: With CacheModule and CacheInterceptor

    Use a shared store like Redis with several instances, and decide how to invalidate keys on writes.

  36. 36. How do you move slow work, like sending emails, to a background queue in Nest?

    Correct answer: With @nestjs/bullmq and a @Processor() class

    Jobs survive restarts in Redis, can be retried with backoff and processed by separate worker instances.

  37. 37. What does @nestjs/event-emitter provide?

    Correct answer: In-process events handled with @OnEvent()

    It decouples modules inside one process. Events are lost on crash, so use a queue or broker for work that must happen.

  38. 38. How do you push live updates to the browser over HTTP in Nest?

    Correct answer: With @Sse() on a handler returning an Observable

    For two-way communication use WebSocket gateways (@WebSocketGateway() with @SubscribeMessage()).

  39. 39. What is a WebSocket gateway in Nest?

    @WebSocketGateway()
    export class ChatGateway {
      @SubscribeMessage("message")
      handle(@MessageBody() text: string) {}
    }

    Correct answer: A provider that handles WebSocket messages

    Guards, pipes, interceptors and filters work in gateways too. With several instances, use a Redis adapter to broadcast.

  40. 40. What's the difference between unit and e2e tests in a Nest project?

    Correct answer: Unit tests mock dependencies; e2e boots the whole app

    E2e tests catch wiring problems: missing providers, wrong guards or pipes, real validation.

  41. 41. In an e2e test, why apply the same global pipes and filters as in main.ts?

    Correct answer: main.ts settings aren't part of AppModule

    Registering global pipes and filters as APP_PIPE/APP_FILTER providers inside the module avoids this mismatch.

  42. 42. How do you override a guard in a test to simulate an authenticated user?

    Correct answer: .overrideGuard(JwtAuthGuard).useValue(...)

    Similar helpers exist for pipes, interceptors and filters: overridePipe, overrideInterceptor, overrideFilter.

  43. 43. Why is it useful to test against a real database in Docker for repository code?

    Correct answer: Mocks don't catch wrong queries or constraints

    Use transactions rolled back after each test or a fresh schema per test run to keep tests isolated.

  44. 44. What's the difference between @MessagePattern and @EventPattern in Nest microservices?

    Correct answer: @MessagePattern expects a reply; @EventPattern doesn't

    On the client side, client.send() expects a response and client.emit() publishes an event.

  45. 45. Which transports do Nest microservices support out of the box?

    Correct answer: TCP, Redis, NATS, RabbitMQ, Kafka and gRPC

    Custom transporters can be written too. The handler code stays the same; only the transport configuration changes.

  46. 46. What is a hybrid application in Nest?

    Correct answer: One app serving HTTP and microservice transports

    Call app.startAllMicroservices() before app.listen(). By default, global enhancers aren't shared with microservices unless you enable inheritAppConfig.

  47. 47. What's the difference between code-first and schema-first GraphQL in Nest?

    Correct answer: Code-first builds the schema from TypeScript classes

    Code-first keeps one source of truth in TypeScript; schema-first suits teams that design the schema as a contract first.

  48. 48. What does @ResolveField() do in a GraphQL resolver?

    Correct answer: Resolves one field of a type separately

    Without batching, resolving author for 100 posts triggers 100 queries.

  49. 49. How do you validate environment variables at startup with @nestjs/config?

    Correct answer: Pass a validationSchema to forRoot()

    Failing fast at startup is better than crashing on the first request that needs a missing variable.

  50. 50. How do you organize configuration into typed namespaces?

    Correct answer: With registerAs() and ConfigType<typeof ...>

    Typed config objects avoid typos in key strings and keep related settings together.

  51. 51. Which API versioning strategies does Nest support?

    Correct answer: URI, header, media type and custom

    Enable with app.enableVersioning({ type: VersioningType.URI }) and mark controllers or routes with @Version('2').

  52. 52. What does the @nestjs/swagger CLI plugin do?

    Correct answer: Adds Swagger metadata at compile time

    It also can read JSDoc comments as descriptions. Enable it in nest-cli.json.

  53. 53. Why might you switch a Nest app from Express to Fastify?

    Correct answer: For higher throughput and lower overhead

    Create the app with new FastifyAdapter(). Check that libraries you use (file upload, sessions) have Fastify equivalents.

  54. 54. What problem can a 'shared module' that exports everything cause?

    Correct answer: Hidden coupling between all the features

    Prefer small focused modules that export only what others need.

  55. 55. What is a Nest monorepo (workspace) used for?

    Correct answer: Hosting several apps and shared libraries

    nest g app worker and nest g library common create the structure. Nx and Turborepo are popular alternatives.

  56. 56. What is a standalone Nest application?

    Correct answer: An app context without an HTTP server

    You still get DI and providers, so scripts can reuse services, for example to run a data migration.

  57. 57. How can you read the current request ID in deep services without passing it through every call?

    Correct answer: With AsyncLocalStorage, e.g. nestjs-cls

    ALS follows the async context of the request without the performance cost of request-scoped providers.

  58. 58. How do you enable graceful shutdown with health checks in Kubernetes for Nest?

    Correct answer: Call app.enableShutdownHooks() and use Terminus

    Close connections in onModuleDestroy or onApplicationShutdown, and give in-flight requests time to finish.

  59. 59. What is middleware bound in configure(consumer) NOT able to see?

    Correct answer: Which handler will process the request

    That's why role checks belong in guards. Middleware suits generic things like logging, request IDs or body parsing.

  60. 60. How do you exclude some routes from a middleware?

    Correct answer: With .exclude(...) on consumer.apply(Mw)

    forRoutes accepts paths, controllers or route info objects.

  61. 61. What does @nestjs/cqrs provide?

    Correct answer: Command, query and event buses

    It's useful for complex domains with many workflows. For simple CRUD it adds ceremony without much benefit.

  62. 62. How do you compress responses in Nest?

    Correct answer: With the compression middleware or the proxy

    In high-traffic setups, compression at a proxy or CDN saves Node.js CPU.

  63. 63. What's a sign that a Nest controller is doing too much?

    Correct answer: It holds business rules and database queries

    Thin controllers are easier to test, and the same logic can be reused by queues, schedulers or GraphQL resolvers.

  64. 64. How do you set security headers in a Nest app?

    Correct answer: With the helmet package

    Register Helmet before other middleware or routes so its headers apply to every response.

  65. 65. What does @nestjs/schedule offer besides @Cron?

    Correct answer: @Interval(), @Timeout() and SchedulerRegistry

    Scheduling is per process. For distributed systems, combine it with a lock or use a queue with repeatable jobs.

  66. 66. How can you log every request with timing in Nest?

    Correct answer: With middleware or an interceptor

    Libraries like nestjs-pino do this out of the box with structured JSON logs and request IDs.

  67. 67. Why might ValidationPipe not reject unknown query parameters by default?

    Correct answer: Without forbidNonWhitelisted, extras pass through

    Enable both options globally to make the API strict about its inputs.

  68. 68. What does @Controller({ path: 'users', version: '2' }) require to work?

    Correct answer: Versioning enabled with app.enableVersioning()

    Without enabling versioning, version metadata is ignored and routes conflict.

  69. 69. What's the purpose of nest build with webpack or SWC in production?

    Correct answer: Compile TypeScript so production runs plain JS

    Running TypeScript directly in production adds startup cost and dev-only dependencies.

  70. 70. After upgrading to NestJS 11 (Express 5), a route @Get('files/*') stops matching as before. Why?

    Correct answer: Express 5 requires named wildcards like files/*splat

    Express 5 uses a newer path-to-regexp. Optional parts use braces too, like /users{/:id}. The Nest migration guide lists such changes.

  71. 71. With several app instances, why does the default throttler storage give wrong limits?

    Correct answer: Each process keeps its own in-memory counters

    Configure a Redis storage for ThrottlerModule, and trust the proxy so the real client IP is used.

  72. 72. Which built-in pipe rejects a route param that isn't a valid UUID?

    Correct answer: ParseUUIDPipe

    Other built-ins: ParseBoolPipe, ParseArrayPipe, ParseEnumPipe, ParseFloatPipe, ParseDatePipe.

  73. 73. When are lazy-loaded modules (LazyModuleLoader) useful?

    Correct answer: In serverless functions, to cut cold-start time

    Lazy modules don't register controllers or routes, so they suit services used from code, not HTTP endpoints.

  74. 74. Interceptors are bound globally, on a controller and on a route. In what order does their 'after' logic run?

    Correct answer: In reverse: route, then controller, then global

    Before the handler they run global → controller → route; the response flows back out through the same layers in reverse.

  75. 75. What does @Optional() on a constructor parameter do?

    Correct answer: Nest injects undefined if there's no provider

    Useful for optional integrations, e.g. a module that works with or without a configured metrics client.