Top 20 NestJS Interview Questions and Answers

Learn and master the top 20 NestJS framework interview questions along with detailed answers with code snippets.

1. What is NestJS?

 NestJS is a progressive Node.js framework for building efficient and scalable server-side applications.

It uses modern JavaScript/TypeScript features and follows the modular architecture pattern.

2. What are the key features of NestJS?

   Some key features of NestJS include:

     – Modular and scalable architecture

     – TypeScript support

     – Dependency Injection (DI)

     – Decorators for defining routes, middleware, etc.

     – Built-in support for WebSockets, GraphQL, and more

     – Middleware and Guard support for request/response handling

     – Extensive ecosystem with numerous libraries and plugins

3. How do you create a new NestJS application?

You can create a new NestJS application using the Nest CLI (Command Line Interface) tool.

Run the following command:

npx nest new project-name

4. What is Dependency Injection (DI) in NestJS?

Dependency Injection is a design pattern used in NestJS for managing dependencies and promoting modular, reusable code.

It allows you to inject instances of classes into other classes, making them more independent and testable.

5. How do you define a provider in NestJS?

Providers are classes or values that can be injected into other classes.

To define a provider, use the `@Injectable()` decorator.

Here’s an example:

import { Injectable } from '@nestjs/common';
     
 @Injectable()
 
 export class MyService {
     // ...
  }

6. How do you inject a dependency in NestJS?

To inject a dependency, you can use constructor-based injection.

Simply declare the dependency as a parameter in the constructor of the consuming class.

NestJS will automatically resolve and inject the dependency.

Here’s an example:

     import { Injectable } from '@nestjs/common';
     import { MyService } from './my.service';

     @Injectable()

     export class MyController {

       constructor(private readonly myService: MyService) {}

       // ...

     }

7. How do you define a controller in NestJS?

Controllers handle incoming requests and define the API endpoints.

To define a controller, use the `@Controller()` decorator.

Here’s an example:

     import { Controller, Get } from '@nestjs/common';
     @Controller('users')

     export class UserController {

       @Get()

       findAll() {

         return 'This is the list of users';

       }

     }

8. How do you define a route in NestJS?

See also  Top 30 SEO Interview Questions and Answers

Routes are defined using decorators such as `@Get()`, `@Post()`, etc., inside controller classes.

These decorators specify the HTTP method and the route path.

Here’s an example:

     import { Controller, Get } from '@nestjs/common';
     @Controller('users')

     export class UserController {

       @Get()

       findAll() {

         return 'This is the list of users';

       }

     }

9. How do you handle request parameters in NestJS?

Request parameters can be accessed using decorators such as `@Param()`, `@Query()`, etc., inside controller methods.

These decorators extract the values from the request URL or query string. Here’s an example:

     import { Controller, Get, Param } from '@nestjs/common';
     @Controller('users')

     export class UserController {

       @Get(':id')

       findById(@Param('id') id: string) {

         return `User ID: ${id}`;

       }

     }

10. How do you handle request bodies in NestJS?

Request bodies can be accessed using decorators such as `@Body()` inside controller methods.

This decorator allows you to extract the payload sent in the request body. Here’s an example:

      import { Controller, Post, Body } from '@nestjs/common';
      @Controller('users')

      export class UserController {

        @Post()

        createUser(@Body() user: UserDto) {

          // Process the user object

        }

      }

11. How do you handle request headers in NestJS?

Request headers can be accessed using decorators such as `@Headers()` inside controller methods.

This decorator allows you to extract the values of specific headers. Here’s an example:

      import { Controller, Get, Headers } from '@nestjs/common';
      @Controller('users')

      export class UserController {

        @Get()

        getUserAgent(@Headers('user-agent') userAgent: string) {

          return `User Agent: ${userAgent}`;

        }

      }

12. How do you handle request validation in NestJS?

Request validation can be done using various validation libraries such as `class-validator` and `class-transformer`.

You can use decorators such as `@IsString()`, `@IsNumber()`, etc., to validate request data.

Here’s an example using `class-validator`:

      import { Controller, Post, Body } from '@nestjs/common';
      import { IsString, IsEmail } from 'class-validator';

      class CreateUserDto {

        @IsString()

        name: string;

        @IsEmail()

        email: string;

      }

      @Controller('users')

      export class UserController {

        @Post()

        createUser(@Body() user: CreateUserDto) {

          // Process the validated user object

        }

      }

13. How do you handle error responses in NestJS?

See also  Top 30 Mocha JS Interview Questions and Answers

Error responses can be handled using exception filters or global exception handlers.

You can throw custom exceptions or use built-in exceptions like `HttpException` to return appropriate error responses.

Here’s an example using a global exception filter:

      import { Catch, HttpException, ExceptionFilter, ArgumentsHost } from '@nestjs/common';
      @Catch(HttpException)

      export class HttpExceptionFilter implements ExceptionFilter {

        catch(exception: HttpException, host: ArgumentsHost) {

          const ctx = host.switchToHttp();

          const response = ctx.getResponse();

          const status = exception.getStatus();

          response.status(status).json({

            statusCode: status,

            message: exception.message,

          });

        }

      }

14. How do you handle authentication and authorization in NestJS?

Authentication and authorization can be handled using middleware or guards.

Middleware functions intercept requests and perform authentication-related tasks.

Guards validate if a user is authorized to access a specific route.

Here’s an example using a guard:

      import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
      @Injectable()

      export class AuthGuard implements CanActivate {

        canActivate(context: ExecutionContext): boolean {

          const request = context.switchToHttp().getRequest();

          // Perform authentication and authorization checks

          return true; // or false if not authorized

        }

      }

15. How do you handle file uploads in NestJS?

File uploads can be handled using libraries like `multer` or `nestjs/multer`.

These libraries provide middleware that allows you to handle file uploads in NestJS.

Here’s an example using `nestjs/multer`:

      import { Controller, Post, UseInterceptors, UploadedFile } from '@nestjs/common';
      import { FileInterceptor } from '@nestjs/platform-express';

      @Controller('files')

      export class FileController {

        @Post('upload')

        @UseInterceptors(FileInterceptor('file'))

        uploadFile(@UploadedFile() file: Express.Multer.File) {

          // Process the uploaded file

        }

      }

16. How do you handle WebSocket connections in NestJS?

WebSocket connections can be handled using the `@WebSocketGateway()` decorator and event handlers.

You can define event handlers for various WebSocket events like `@OnGatewayConnection()`, `@OnGatewayDisconnect()`, etc.

Here’s an example:

      import { WebSocketGateway, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
      @WebSocketGateway()

      export class MyGateway implements OnGatewayConnection, OnGatewayDisconnect {

        handleConnection(client: WebSocket) {

          // Handle connection event

        }

        handleDisconnect(client: WebSocket) {

          // Handle disconnect event

        }

      }

17. How do you implement caching in NestJS?

See also  Top 15 CSS Animations Interview Questions and Answers

Caching can be implemented using various caching strategies and libraries such as `nestjs/cache` or `redis`.

You can use decorators like `@Cacheable()`, `@CacheKey()`, etc., to cache method results.

Here’s an example using `nestjs/cache`:

      import { CacheInterceptor, Controller, Get, UseInterceptors } from '@nestjs/common';
      @Controller('users')

      @UseInterceptors(CacheInterceptor)

      export class UserController {

        @Get()

        @Cacheable({ ttl: 60 }) // Cache response for 60 seconds

        findAll() {

          // Return users

        }

      }

18. How do you implement logging in NestJS?

Logging can be implemented using various logging libraries such as `winston`, `pino`, or the built-in NestJS logger.

You can create a custom logger or use pre-configured loggers.

Here’s an example using the built-in NestJS logger:

      import { Logger } from '@nestjs/common';
      const logger = new Logger('App');

      @Controller('users')

      export class UserController {

        constructor() {

          logger.log('UserController initialized');

        }

        // ...

      }

19. How do you handle environment variables in NestJS?

Environment variables can be accessed using the `ConfigService` provided by the `@nestjs/config` package.

This package allows you to load and validate environment variables from various sources.

Here’s an example:

      import { ConfigService } from '@nestjs/config';
      import { Injectable } from '@nestjs/common';

      @Injectable()

      export class MyService {

        constructor(private readonly configService: ConfigService) {

          const apiKey = configService.get('API_KEY');

          // Use the API key

        }

      }

20. How do you implement unit testing in NestJS?

Unit testing in NestJS can be done using testing frameworks like Jest or Mocha.

You can use built-in testing utilities provided by NestJS like `@nestjs/testing` to create test modules, inject dependencies, and perform assertions.

Here’s an example using Jest:

      import { Test, TestingModule } from '@nestjs/testing';
      import { MyService } from './my.service';

      describe('MyService', () => {

        let service: MyService;

        beforeEach(async () => {

          const module: TestingModule = await Test.createTestingModule({

            providers: [MyService],

          }).compile();

          service = module.get<MyService>(MyService);

        });

        it('should return "Hello, World!"', () => {

          expect(service.getHello()).toBe('Hello, World!');

        });

      });