1. Basic NestJS Questions
1. What is NestJS?
NestJS is a progressive Node.js framework for building scalable and maintainable backend applications using TypeScript. It is built on top of Express.js (or Fastify) and follows an Angular-inspired modular architecture.
2. What are the main features of NestJS?
TypeScript support
Modular architecture
Built-in Dependency Injection
Support for Express.js & Fastify
Middleware and Guards
WebSockets and GraphQL support
3. What is the entry point of a NestJS application?
The entry point is the main.ts
file. It bootstraps the 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();
4. What are modules in NestJS?
Modules in NestJS are used to organize the application into logical units. Each module is a class decorated with @Module()
.
Example:
import { Module } from '@nestjs/common';
@Module({
imports: [],
controllers: [],
providers: [],
})
export class AppModule {}
5. How do you create a new module in NestJS?
Run the following CLI command:
nest g module <module-name>
2. Controllers & Routes
6. What are controllers in NestJS?
Controllers handle incoming HTTP requests and return responses. They are decorated with @Controller()
.
7. How do you define a simple controller in NestJS?
import { Controller, Get } from '@nestjs/common';
@Controller('users')
export class UserController {
@Get()
findAll() {
return 'This action returns all users';
}
}
8. How do you define dynamic routes in NestJS?
@Get(':id')
findOne(@Param('id') id: string) {
return `User with ID ${id}`;
}
9. What are route parameters and how do you access them?
Route parameters are dynamic values in a route. You access them using @Param()
.
Example:
@Get(':id')
getUser(@Param('id') id: string) {
return `User ID: ${id}`;
}
10. What is the purpose of the @Body()
decorator?
@Body()
extracts the request body data.
Example:
@Post()
createUser(@Body() userDto: CreateUserDto) {
return userDto;
}
3. Services & Dependency Injection
11. What are services in NestJS?
Services handle business logic and are used for code reusability. They are decorated with @Injectable()
.
12. How do you create a service in NestJS?
Run:
nest g service <service-name>
13. How do you inject a service into a controller?
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
getUsers() {
return this.userService.findAll();
}
}
14. What is Dependency Injection in NestJS?
It allows NestJS to automatically provide required dependencies, improving modularity and testability.
15. What is the @Injectable()
decorator?
It marks a class as a provider that can be injected into other components.
4. Middleware, Guards, and Interceptors
16. What is middleware in NestJS?
Middleware is a function that runs before the request reaches the controller.
17. How do you create middleware in NestJS?
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(`Request...`);
next();
}
}
18. What are guards in NestJS?
Guards are used for authentication & authorization.
Example:
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
return true; // or false based on logic
}
}
19. How do you apply guards to a route?
@UseGuards(AuthGuard)
@Get('protected')
getProtectedData() {
return 'This is protected data';
}
20. What are interceptors in NestJS?
Interceptors modify requests or responses before reaching the client.
Example:
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before request...');
return next.handle();
}
}
5. Database & ORM Integration
21. What are the supported ORMs in NestJS?
TypeORM
Sequelize
Prisma
Mongoose
22. How do you configure TypeORM in NestJS?
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'user',
password: 'password',
database: 'test',
entities: [User],
synchronize: true,
}),
],
})
export class AppModule {}
23. What is the @Entity()
decorator in TypeORM?
It marks a class as a database entity.
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
}
24. How do you create a repository in NestJS?
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
) {}
findAll() {
return this.userRepository.find();
}
}
25. How do you integrate MongoDB with NestJS?
@Module({
imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
})
export class AppModule {}
6. Testing in NestJS
26. What is Jest and why is it used in NestJS?
Jest is a testing framework used for writing unit and integration tests.
27. How do you write a simple test in NestJS?
describe('UserService', () => {
it('should return users', async () => {
expect(await userService.findAll()).toEqual([]);
});
});
28. How do you mock a service in Jest?
jest.mock('./user.service');
7. Advanced Topics
29. What is GraphQL and how does NestJS support it?
GraphQL is a query language for APIs. NestJS provides @nestjs/graphql
package.
@Resolver()
export class UserResolver {
@Query(() => String)
sayHello() {
return 'Hello, GraphQL!';
}
}
30. What are microservices in NestJS?
NestJS supports Microservice Architecture using Redis, MQTT, Kafka, and gRPC.
8. Real-Time Features in NestJS
31. How does NestJS support WebSockets?
NestJS provides built-in WebSocket support using @nestjs/websockets
.
Example:
@WebSocketGateway()
export class ChatGateway {
@SubscribeMessage('message')
handleMessage(@MessageBody() data: string): string {
return `Received: ${data}`;
}
}
32. What is the @SubscribeMessage()
decorator?
It listens for WebSocket events and handles real-time messages.
9. Security in NestJS
33. How do you implement authentication in NestJS?
You can use JWT-based authentication with @nestjs/passport
and passport-jwt
.
Example:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'your_secret_key',
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
34. How do you secure API routes using JWT?
Use the AuthGuard
with @UseGuards()
.
@UseGuards(AuthGuard('jwt'))
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
35. What is CSRF and how do you prevent it in NestJS?
Cross-Site Request Forgery (CSRF) is an attack where malicious requests are made on behalf of an authenticated user.
✅ Use CSRF tokens with csurf
middleware.
✅ Implement SameSite cookies.
app.use(csurf());
36. How do you handle rate-limiting in NestJS?
Use @nestjs/throttler
to limit API requests and prevent DDoS attacks.
@Throttle(5, 60) // 5 requests per 60 seconds
@Get('data')
getData() {
return 'Rate-limited data';
}
37. How do you encrypt passwords in NestJS?
Use bcrypt
to hash passwords before storing them.
const salt = await bcrypt.genSalt();
const hashedPassword = await bcrypt.hash(password, salt);
10. Logging & Performance Optimization
38. How do you implement logging in NestJS?
Use the built-in Logger
service.
import { Logger } from '@nestjs/common';
const logger = new Logger('AppLogger');
logger.log('Application started');
39. How do you enable CORS in NestJS?
const app = await NestFactory.create(AppModule);
app.enableCors();
40. How do you optimize NestJS performance?
✅ Use Fastify instead of Express
✅ Enable caching with cache-manager
✅ Optimize database queries
✅ Use compression middleware
import * as compression from 'compression';
app.use(compression());
11. Microservices & Event-Driven Architecture
41. How do you create a microservice in NestJS?
Use @nestjs/microservices
and NestFactory.createMicroservice()
.
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP,
options: { port: 3001 },
});
await app.listen();
42. What are message patterns in microservices?
They define how services communicate.
@MessagePattern({ cmd: 'sum' })
sumNumbers(@Payload() data: number[]) {
return data.reduce((a, b) => a + b, 0);
}
43. What transport layers does NestJS microservices support?
✅ TCP
✅ Redis
✅ Kafka
✅ gRPC
✅ MQTT
12. Deployment & Configuration Management
44. How do you deploy a NestJS application?
✅ Use Docker for containerization.
✅ Deploy using Heroku, AWS, or DigitalOcean.
FROM node:18
WORKDIR /app
COPY . .
RUN npm install
CMD ["npm", "start"]
45. How do you configure environment variables in NestJS?
Use @nestjs/config
to load .env
variables.
ConfigModule.forRoot({
isGlobal: true,
});
46. How do you set up a CI/CD pipeline for a NestJS project?
✅ Use GitHub Actions or Jenkins.
✅ Automate testing and deployment.
Example GitHub Action:
name: Deploy
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install
- run: npm test
13. Miscellaneous & Best Practices
47. How do you implement caching in NestJS?
Use cache-manager
for in-memory caching.
import { CacheModule } from '@nestjs/cache-manager';
@Module({
imports: [CacheModule.register()],
})
48. How do you implement database transactions in NestJS?
With TypeORM:
await this.connection.transaction(async manager => {
await manager.save(user);
await manager.save(order);
});
49. How do you handle errors globally in NestJS?
Use exception filters.
@Catch(HttpException)
export class HttpErrorFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
response.status(exception.getStatus()).json({
message: exception.message,
});
}
}
50. What are the best practices for writing NestJS applications?
✅ Use modules to organize your code.
✅ Follow SOLID principles for maintainability.
✅ Use DTOs for data validation.
✅ Implement logging and monitoring.
✅ Write unit and integration tests.
Final Thoughts 💡
NestJS is a powerful framework for building scalable backend applications. These 50 questions cover everything from basic concepts to advanced architecture, security, and microservices.