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. 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. 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. What is
ExecutionContextused for?Correct answer: Reading the current handler, class and request
context.switchToHttp().getRequest(),context.getHandler(),context.getClass()andcontext.getType()are the common calls.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
ReflectorgetAllAndOverridelets a method-level value override a class-level one;getAllAndMergecombines them.5. How do you register a global guard that can inject other providers?
providers: [{ provide: APP_GUARD, useClass: JwtAuthGuard }]Correct answer: With the
APP_GUARDtoken in a module's providersapp.useGlobalGuards()takes an instance created outside the DI container, so its dependencies aren't injected.APP_PIPE,APP_INTERCEPTORandAPP_FILTERwork the same way.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. 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. How can an interceptor add a timeout to slow handlers?
Correct answer: With the RxJS
timeoutoperator onnext.handle()This stops waiting for the result, but the underlying work keeps running unless you also cancel it (for example with an
AbortSignal).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
createParamDecoratorfunctionCustom decorators can also accept data (
@User('email')) and be combined with pipes, e.g.@User(new ValidationPipe()).10. How do you combine several decorators into one, e.g. guards plus Swagger annotations?
Correct answer: With the
applyDecorators(...)helperA single
@Auth('admin')decorator can set roles metadata, apply guards and document the route.11. When would you use
useFactoryfor 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. What is
useExistingfor?Correct answer: An alias token for an existing provider instance
For example, expose a
LoggerServiceinterface token that points to an existingPinoLoggerinstance.13. Why inject an interface-like dependency by token instead of by class?
@Inject(PAYMENT_GATEWAY) private readonly payments: PaymentGatewayCorrect answer: TypeScript interfaces don't exist at runtime
Register
{ provide: PAYMENT_GATEWAY, useClass: StripeGateway }in production and a fake in tests.14. What is a dynamic module?
Correct answer: A module configured at runtime via a static method
ConfigModule.forRoot(),TypeOrmModule.forFeature()andJwtModule.register()are dynamic modules.ConfigurableModuleBuilderhelps write your own.15. What's the usual convention for
forRoot,registerandforFeature?Correct answer:
forRootonce,registerper module,forFeaturefor partsIt's a convention, not a rule, but following it makes modules predictable for other developers.
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. 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. vianestjs-cls) is often a cheaper option.18. How do you resolve a circular dependency between two providers?
Correct answer: Refactor, or use
forwardRef()on both sidesCycles usually mean responsibilities are mixed. Extracting the shared logic into a third provider is the cleaner fix.
19. What does
ModuleReflet 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. Which lifecycle hook is the right place to open a connection that other modules rely on during startup?
Correct answer:
onModuleInitor an async factoryConstructors can't be async. Nest awaits async
onModuleInithooks before callingonApplicationBootstrap.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. 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. How can a custom validation rule check something asynchronous, like 'email is not taken'?
Correct answer: With a custom
class-validatorconstraint classAsync checks improve error messages but have race conditions. The database constraint must catch concurrent duplicates.
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. What does
@Expose({ groups: ['admin'] })withClassSerializerInterceptorallow?Correct answer: Showing fields only for a given serialization group
Set the groups per route with
@SerializeOptions({ groups: [...] }).26. How do you write a global filter that formats all errors as RFC 9457 problem details?
Correct answer: A
@Catch()class registered withAPP_FILTERMap
HttpExceptions to their status, unknown errors to 500 with a generic message, and log the real error with a request ID.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. 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. How does Passport fit into Nest authentication?
Correct answer:
@nestjs/passportwraps strategies as guardsA strategy class extends
PassportStrategy(Strategy)and implementsvalidate(), whose return value becomesrequest.user.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. 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. 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-transactionaluse ALS to propagate it.33. Why is
synchronize: truein TypeORM dangerous in production?Correct answer: It alters the schema on startup and can drop data
Use migrations in production.
synchronizeis only convenient for local prototypes.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. How do you cache GET responses in Nest?
Correct answer: With
CacheModuleandCacheInterceptorUse a shared store like Redis with several instances, and decide how to invalidate keys on writes.
36. How do you move slow work, like sending emails, to a background queue in Nest?
Correct answer: With
@nestjs/bullmqand a@Processor()classJobs survive restarts in Redis, can be retried with backoff and processed by separate worker instances.
37. What does
@nestjs/event-emitterprovide?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. How do you push live updates to the browser over HTTP in Nest?
Correct answer: With
@Sse()on a handler returning an ObservableFor two-way communication use WebSocket gateways (
@WebSocketGateway()with@SubscribeMessage()).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. 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. In an e2e test, why apply the same global pipes and filters as in
main.ts?Correct answer:
main.tssettings aren't part ofAppModuleRegistering global pipes and filters as
APP_PIPE/APP_FILTERproviders inside the module avoids this mismatch.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. 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. What's the difference between
@MessagePatternand@EventPatternin Nest microservices?Correct answer:
@MessagePatternexpects a reply;@EventPatterndoesn'tOn the client side,
client.send()expects a response andclient.emit()publishes an event.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. What is a hybrid application in Nest?
Correct answer: One app serving HTTP and microservice transports
Call
app.startAllMicroservices()beforeapp.listen(). By default, global enhancers aren't shared with microservices unless you enableinheritAppConfig.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. What does
@ResolveField()do in a GraphQL resolver?Correct answer: Resolves one field of a type separately
Without batching, resolving
authorfor 100 posts triggers 100 queries.49. How do you validate environment variables at startup with
@nestjs/config?Correct answer: Pass a
validationSchematoforRoot()Failing fast at startup is better than crashing on the first request that needs a missing variable.
50. How do you organize configuration into typed namespaces?
Correct answer: With
registerAs()andConfigType<typeof ...>Typed config objects avoid typos in key strings and keep related settings together.
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. What does the
@nestjs/swaggerCLI 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. 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. 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. What is a Nest monorepo (workspace) used for?
Correct answer: Hosting several apps and shared libraries
nest g app workerandnest g library commoncreate the structure. Nx and Turborepo are popular alternatives.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. How can you read the current request ID in deep services without passing it through every call?
Correct answer: With
AsyncLocalStorage, e.g.nestjs-clsALS follows the async context of the request without the performance cost of request-scoped providers.
58. How do you enable graceful shutdown with health checks in Kubernetes for Nest?
Correct answer: Call
app.enableShutdownHooks()and use TerminusClose connections in
onModuleDestroyoronApplicationShutdown, and give in-flight requests time to finish.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. How do you exclude some routes from a middleware?
Correct answer: With
.exclude(...)onconsumer.apply(Mw)forRoutesaccepts paths, controllers or route info objects.61. What does
@nestjs/cqrsprovide?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. How do you compress responses in Nest?
Correct answer: With the
compressionmiddleware or the proxyIn high-traffic setups, compression at a proxy or CDN saves Node.js CPU.
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. How do you set security headers in a Nest app?
Correct answer: With the
helmetpackageRegister Helmet before other middleware or routes so its headers apply to every response.
65. What does
@nestjs/scheduleoffer besides@Cron?Correct answer:
@Interval(),@Timeout()andSchedulerRegistryScheduling is per process. For distributed systems, combine it with a lock or use a queue with repeatable jobs.
66. How can you log every request with timing in Nest?
Correct answer: With middleware or an interceptor
Libraries like
nestjs-pinodo this out of the box with structured JSON logs and request IDs.67. Why might
ValidationPipenot reject unknown query parameters by default?Correct answer: Without
forbidNonWhitelisted, extras pass throughEnable both options globally to make the API strict about its inputs.
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. What's the purpose of
nest buildwith 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. 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/*splatExpress 5 uses a newer
path-to-regexp. Optional parts use braces too, like/users{/:id}. The Nest migration guide lists such changes.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. Which built-in pipe rejects a route param that isn't a valid UUID?
Correct answer:
ParseUUIDPipeOther built-ins:
ParseBoolPipe,ParseArrayPipe,ParseEnumPipe,ParseFloatPipe,ParseDatePipe.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. 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. What does
@Optional()on a constructor parameter do?Correct answer: Nest injects
undefinedif there's no providerUseful for optional integrations, e.g. a module that works with or without a configured metrics client.