Prepare for Your Next NestJS Interview with These Essential Questions
This comprehensive guide features 30 NestJS interview questions covering basic, intermediate, and advanced topics. Whether you’re a fresher, have 1-3 years of experience, or are a seasoned developer with 3-6+ years, these questions will help you demonstrate your NestJS expertise to companies like Zoho, Paytm, Salesforce, and Atlassian.
Basic NestJS Interview Questions (Questions 1-10)
Question 1: What is NestJS?
NestJS is a progressive Node.js framework for building efficient, scalable server-side applications using TypeScript. It combines elements of Object-Oriented Programming (OOP), Functional Programming (FP), and Functional Reactive Programming (FRP).
Question 2: What are the main components of a NestJS application?
The main components are Modules, Controllers, Providers (Services), Pipes, Guards, Interceptors, and Exception Filters. These components work together to create a modular, testable architecture.
Question 3: How do you declare a class as a controller in NestJS?
You use the @Controller() decorator on a class to declare it as a controller.
import { Controller, Get } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get()
findAll() {
return 'All users';
}
}
Question 4: What is the purpose of the @Injectable() decorator?
The @Injectable() decorator marks a class as a provider that can be injected into other classes through NestJS’s dependency injection system.
Question 5: What is a Module in NestJS?
A Module is a class annotated with @Module() that serves as a container for related components like controllers, providers, and other modules. Modules help organize code and promote reusability.
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {}
Question 6: What is Dependency Injection in NestJS?
Dependency Injection (DI) is a design pattern where dependencies are provided to a class rather than created within it. NestJS’s built-in DI container automatically resolves and injects dependencies, making code more modular and testable.
Question 7: What is the entry file of a NestJS application?
The entry file is typically main.ts, where you bootstrap the NestJS application using NestFactory.create().
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
Question 8: How do you define a service or component that can be injected?
You create a class decorated with @Injectable() and register it in a module’s providers array.
Question 9: What are Pipes in NestJS?
Pipes are classes that implement the PipeTransform interface. They transform and validate incoming data, such as converting query parameters or validating request bodies.
Question 10: What are Guards in NestJS?
Guards determine whether a request should be handled by the route handler. They have a single responsibility: decide if execution should continue based on authorization logic.
Intermediate NestJS Interview Questions (Questions 11-20)
Question 11: What is the difference between controllers and providers?
Controllers handle incoming HTTP requests and return responses to the client. Providers (services) contain the business logic and are injected into controllers for code reusability.
Question 12: How do you implement custom validation logic for DTOs?
Create custom validation pipes and decorators using class-validator and class-transformer packages. Register them globally or at the controller/route level.
import { IsEmail, IsNotEmpty } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsNotEmpty()
name: string;
}
Question 13: What are Interceptors in NestJS?
Interceptors wrap the execution of request handlers to modify incoming requests or outgoing responses. They can log requests, transform responses, or add caching functionality.
Question 14: How do you make an ExceptionFilter global in NestJS?
Apply the @Catch() decorator to catch specific exceptions and bind it globally using app.useGlobalFilters(new HttpExceptionFilter()) in main.ts.
Question 15: What is the purpose of DTOs (Data Transfer Objects) in NestJS?
DTOs define the shape of data exchanged between client and server. They ensure type safety, validation, and documentation through TypeScript interfaces and decorators.
Question 16: How does NestJS handle CORS?
NestJS provides built-in CORS support through the CorsOptions configuration. Enable it in main.ts using app.enableCors().
app.enableCors({
origin: 'http://localhost:3000',
credentials: true,
});
Question 17: What is the @InjectRepository() decorator used for?
The @InjectRepository() decorator from TypeORM is used to inject a repository into a service, providing access to database operations for a specific entity.
Question 18: What are the main responsibilities of a Pipe?
Pipes transform pure data (like strings) into complex data (like objects) and validate incoming data before it reaches the route handler.
Question 19: How do you structure a large-scale NestJS application?
Use modular architecture with feature modules for each domain, shared modules for common functionality, core module for global services, and configuration module for environment management.
Question 20: What is the purpose of the @nestjs/jwt package?
The @nestjs/jwt package provides JWT (JSON Web Token) authentication utilities, including guards, strategies, and token generation for securing NestJS applications.
Advanced NestJS Interview Questions (Questions 21-30)
Question 21: Explain the module lifecycle methods execution order.
The order is: onModuleInit() → onModuleDestroy(). These lifecycle hooks allow modules to perform initialization and cleanup tasks.
Question 22: How do you implement soft deletes in NestJS?
Use TypeORM’s softDelete and restore methods with a deletedAt column instead of permanently removing records from the database.
Question 23: What is the purpose of the ExecutionContext in NestJS?
Create a global exception filter using Asynchronous providers allow dynamic provider creation using factory functions that return Promises. They're useful for database connections or configuration loading. Create a guard implementing The Create an interceptor implementing NestJS supports microservices with patterns like message patterns (RPC, events), transports (TCP, Redis, RabbitMQ, Kafka), service discovery, and saga pattern for distributed transactions. Implement modular monolith with feature modules (orders, payments, inventory), use CQRS pattern, Redis caching, event-driven architecture with RabbitMQ, database per service, API gateway, and comprehensive logging/monitoring with circuit breakers.ExecutionContext
ExecutionContext provides contextual information about the current execution, allowing guards, interceptors, and pipes to access request, response, and other runtime data.Question 24: How do you handle errors globally in NestJS?
@Catch() decorator and register it with app.useGlobalFilters(new AllExceptionsFilter()).Question 25: What are asynchronous providers in NestJS?
providers: [
{
provide: 'DATABASE_CONNECTION',
useFactory: async () => {
return await createConnection();
},
},
]
Question 26: How do you implement authentication guards in NestJS?
CanActivate interface, validate JWT tokens using Passport strategy, and apply it using @UseGuards(AuthGuard('jwt')).Question 27: What is the @Res() decorator used for?
@Res() decorator injects the underlying platform Response object, giving direct access to low-level response methods like setting cookies or headers.Question 28: How do you implement request/response transformation with interceptors?
NestInterceptor, use RxJS map operator to transform data, and bind it globally or per-route.Question 29: Explain NestJS microservices architecture patterns.
Question 30: How would you design a scalable NestJS application for a company like Swiggy?