NestJS interview questions and answers for backend developers
NestJS interview questions focus on how the framework assembles an application: modules that group providers, a dependency injection container that wires them, and a fixed request pipeline of middleware, guards, interceptors, pipes and exception filters. Expect to explain where each kind of logic belongs, how injection scopes and custom providers work, how DTO validation is set up, and how you test a service with its dependencies replaced.
By Evin JohnPublished 8 min read
What NestJS interviews look like
NestJS turns up in TypeScript backend roles at companies that want an opinionated structure on top of Node.js, often teams with Angular experience, since the module and decorator style is similar. Interviews usually start with framework vocabulary, move to a practical task (a small REST module with validation, a guard and a test), and end with design: how you split modules, share configuration, talk to a database and, for some teams, run message-based microservices. A candidate who knows Express but has never thought about dependency injection tends to struggle in the middle part.
- Before the route
- Middleware
- Guards
- Around the handler
- Interceptors (before)
- Pipes
- Controller handler
- Interceptors (after)
- On error
- Exception filters
Fundamentals: modules, providers and controllers
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is a module and what goes in it? | Structure | A class with @Module that declares controllers, providers, the modules it imports and the providers it exports. It is the unit of encapsulation: providers are private unless exported. |
| What is a provider? | DI basics | Anything the container can inject: usually an @Injectable class such as a service or repository, but also a value, a factory result or an alias, registered under a token. |
| Why do I get "Nest can't resolve dependencies"? | Debugging DI | The provider is not in the module, its module does not export it, or the consumer's module does not import that module. Circular imports and missing @Inject on a non-class token are the other usual causes. |
| What does a global module change? | Scope of exports | @Global makes exported providers available everywhere without importing the module. Use it for a few truly shared things, such as config, because it hides dependencies. |
| Middleware versus a guard? | Pipeline roles | Middleware runs before routing details are known and suits logging, raw body handling or request IDs. A guard has the ExecutionContext, so it knows the handler and its metadata, which makes it the place for authorization. |
| What do pipes do? | Arguments | They transform or validate handler arguments before the handler runs, such as ParseIntPipe on a route param or ValidationPipe on a DTO body. Throwing in a pipe stops the request with an error. |
| What is an interceptor good for? | Cross-cutting logic | Code that wraps the handler: timing, response mapping, caching, timeouts and error translation. It works with the RxJS stream the handler returns. |
| How are exceptions turned into responses? | Errors | HttpException and its subclasses become JSON with a status code through the built-in filter. Custom filters catch specific types, such as a database unique violation, and map them to a 409. |
| Express or Fastify under Nest? | Platform | Express is the default with the widest middleware ecosystem. The Fastify adapter often benchmarks faster, but some Express middleware will not work as is. |
A frequent follow-up is the order when several of the same kind apply. Guards, interceptors and pipes bound globally run before controller-level ones, which run before method-level ones. Exception filters work the other way: the filter closest to the route gets the first chance to handle the error.
Intermediate: custom providers, scopes and validation
export const PAYMENTS_CLIENT = Symbol('PAYMENTS_CLIENT');
@Injectable()
export class BillingService {
constructor(@Inject(PAYMENTS_CLIENT) private readonly payments: PaymentsClient) {}
chargeOrder(order: { id: number; totalCents: number }) {
return this.payments.charge({ orderId: order.id, amountCents: order.totalCents });
}
}
@Module({
imports: [ConfigModule],
providers: [
{
provide: PAYMENTS_CLIENT,
useFactory: (config: ConfigService) =>
new PaymentsClient(config.getOrThrow<string>('PAYMENTS_URL')),
inject: [ConfigService],
},
BillingService,
],
exports: [BillingService],
})
export class BillingModule {}- useClass, useValue, useFactory, useExisting: when is each right? useClass swaps an implementation, for example a fake mailer in development. useValue supplies a constant or a mock. useFactory builds something from other providers, often asynchronously. useExisting creates an alias to a provider that already exists.
- Why use a symbol or string token instead of a class? Interfaces vanish at runtime in TypeScript, so there is no class to inject by. A token stands in for the interface, and @Inject names it.
- What are the injection scopes? DEFAULT is one shared instance for the app. REQUEST creates a new instance per request. TRANSIENT gives each consumer its own instance. Singletons are the normal choice.
- What is the hidden cost of a request-scoped provider? Scope bubbles up: anything that injects it also becomes request-scoped, so a whole chain of objects is built on every request. For per-request data such as the current user or a tenant, consider passing it explicitly or using async local storage.
- What is a dynamic module? A module with a static method such as forRoot or register that returns a module definition built from options. forRootAsync takes a factory so options can come from ConfigService.
- How do you validate a request body? Define a DTO class with class-validator decorators and enable ValidationPipe, usually globally. whitelist strips unknown properties, forbidNonWhitelisted rejects them, and transform turns plain objects and strings into the DTO and its types.
- Which lifecycle hooks have you used? onModuleInit for warming a connection, onApplicationBootstrap once everything is ready, and onModuleDestroy or beforeApplicationShutdown for cleanup, which needs enableShutdownHooks to fire on signals.
- How do you manage configuration? ConfigModule with a validation schema so the app refuses to start with a missing variable, typed accessors or namespaced config, and no reading of process.env scattered through services.
export class CreateOrderDto {
@IsString()
@Length(1, 64)
sku: string;
@IsInt()
@Min(1)
quantity: number;
}
// main.ts
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
);
await app.listen(3000);Guards, interceptors and custom decorators
export const ROLES_KEY = 'roles';
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const required = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!required) return true;
const { user } = context.switchToHttp().getRequest();
return required.some((role) => user?.roles?.includes(role));
}
}
@Controller('reports')
@UseGuards(AuthGuard, RolesGuard)
export class ReportsController {
@Get('revenue')
@Roles('finance', 'admin')
revenue() { /* ... */ }
}| Question | What it tests | What a strong answer shows |
|---|---|---|
| Why does the guard return true when no roles are set? | Guard design | Routes without the decorator are open to any authenticated user here. Some teams flip the default and require explicit metadata, which is safer for admin APIs. |
| How do you mark a route public when a global auth guard is on? | Metadata | A @Public decorator that sets metadata, and the global guard checks for it with Reflector before demanding a token. |
| How would you add a timeout to every handler? | Interceptors | An interceptor that pipes the handler's observable through the RxJS timeout operator and maps a timeout error to a 408 or 504 response. |
| How do you shape every response the same way? | Response mapping | An interceptor that maps the handler result into an envelope, or class-transformer serialization with exclude rules so fields like password hashes never leave. |
| How do you get the current user into a handler cleanly? | Param decorators | A custom parameter decorator built with createParamDecorator that reads request.user, so handlers do not touch the raw request. |
| Where does rate limiting fit? | Protection | The throttler module registers a guard, so limits apply before the handler runs. Behind a proxy, make sure the client IP is read correctly. |
Senior and scenario questions
- Two services need each other. What do you do? First ask whether the design is wrong: extract the shared logic into a third provider or use events. forwardRef on both sides resolves the cycle but leaves the coupling in place.
- How do you run a database transaction across several repositories? Pass a transaction-scoped manager or client through the call, use the ORM's transaction callback, or use a library that keeps the transaction in async local storage. Avoid request-scoped repositories just for this.
- MessagePattern versus EventPattern in microservices? MessagePattern is request-response: the caller waits for a reply. EventPattern is fire-and-forget. Transports include TCP, Redis, NATS, Kafka, RabbitMQ and gRPC, and the choice depends on delivery guarantees and ordering, not on Nest.
- How would you split a growing monolith built in Nest? Make module boundaries real first, with no reaching into another module's repositories. Only modules with clean interfaces and their own data are good candidates to extract.
- Scenario: latency rose after someone added tenant handling. Check whether a tenant provider was made request-scoped, which forces many objects to be rebuilt per request. Move the tenant into async local storage or pass it explicitly, and measure again.
- Scenario: unknown fields are being saved to the database. ValidationPipe is missing whitelist, or the handler passes the raw body instead of the DTO. Turn on whitelist and forbidNonWhitelisted, and map DTOs to entities explicitly.
- Scenario: the app does not close database connections on deploy. Shutdown hooks are not enabled, or cleanup sits in a hook that never fires. Enable them and close pools in onModuleDestroy or beforeApplicationShutdown.
- How do you test a module? Unit tests build a testing module with only the providers under test and mocks for the rest. End-to-end tests compile the real AppModule, override external clients, start the app and call it with supertest.
describe('BillingService', () => {
let service: BillingService;
const payments = { charge: jest.fn().mockResolvedValue({ id: 'ch_1' }) };
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [BillingService, { provide: PAYMENTS_CLIENT, useValue: payments }],
}).compile();
service = moduleRef.get(BillingService);
});
it('charges the order total', async () => {
await service.chargeOrder({ id: 7, totalCents: 1250 });
expect(payments.charge).toHaveBeenCalledWith({ orderId: 7, amountCents: 1250 });
});
});Fictional example
- We had four Express services written by four different people, each with its own idea of validation and error handling. Moving to Nest gave us one structure: DTOs with a global ValidationPipe, one exception filter that mapped database errors, and guards for roles. New developers were shipping endpoints in their first week instead of learning four styles. What I would change: we made the logging context provider request-scoped early on, and under load that showed up as extra latency because so many providers depended on it. We replaced it with async local storage. Next time I would also enforce module boundaries with a lint rule from day one.
Getting ready for a NestJS round
- Week 1, structure: build a two-module API, such as users and orders, with exports and imports done by hand. Break the wiring on purpose and read each dependency error until you can predict it.
- Week 1, pipeline: add a logger middleware, an auth guard, a roles guard with metadata, a timing interceptor, ValidationPipe and a custom exception filter. Log from each one and confirm the order.
- Week 2, providers: register a factory provider with forRootAsync and ConfigService, then try each scope and measure what request scope does to latency with a simple load test.
- Week 2, tests and talk: write unit tests with mocked providers and one e2e test with supertest, then practice a five-minute explanation of your module boundaries.
Runtime questions about the event loop and streams sit in Node.js interview questions, and typing questions in TypeScript interview questions. If you are comparing frameworks, Laravel interview questions covers the same backend ideas in PHP.
To rehearse, run a mock round with Natively, an AI interview assistant for Mac and Windows. It writes a transcript of the conversation, so you can check whether you named the pipeline order correctly under pressure. In practice it can read a NestJS exercise from a screenshot and offer a hint or a structure, and with Pro or the free trial it can work from your résumé and the job description. Past sessions and their notes are saved for review.
Questions people ask
What NestJS questions are asked in interviews?
Modules, providers and dependency injection, custom providers and tokens, injection scopes, dynamic modules, the order of middleware, guards, interceptors, pipes and filters, DTO validation, microservice transports and testing modules.
What is the order of the NestJS request lifecycle?
Middleware, then guards, then interceptors before the handler, then pipes, then the handler, then interceptors on the way out. Exception filters handle anything thrown along the way.
What is the difference between a guard and middleware in NestJS?
Middleware runs early and does not know which handler will run. A guard receives the execution context, so it can read handler metadata such as required roles, which makes it the right place for authorization.
What NestJS questions do experienced developers get?
Request-scoped providers and their cost, circular dependencies, transactions across repositories, module boundaries in a large app, microservice patterns and how to test with overridden providers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
