Skip to content

Coding practice

NestJS Coding Questions

12 hands-on challenges with prompts and solution sketches for NestJS interview rounds.

Challenge set

12 coding questions

1. Controller Route

typescript

Create a GET controller method.

@Controller("health")
export class HealthController {
  @Get()
  check() {
    return { ok: true };
  }
}

2. Injectable Service

typescript

Create an injectable service.

@Injectable()
export class UsersService {
  findAll() {
    return [];
  }
}

3. Module Wiring

typescript

Register controller and provider in a module.

@Module({
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}

4. DTO Validation

typescript

Validate a DTO with class-validator.

export class CreateUserDto {
  @IsEmail()
  email!: string;

  @IsString()
  @MinLength(8)
  password!: string;
}

5. Param Decorator

typescript

Read an id param.

@Get(":id")
findOne(@Param("id") id: string) {
  return this.users.findOne(id);
}

6. Guard Stub

typescript

Implement a simple AuthGuard.

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext) {
    const req = context.switchToHttp().getRequest();
    return Boolean(req.headers.authorization);
  }
}

7. Pipe Transform

typescript

Parse an id with ParseIntPipe.

@Get(":id")
findOne(@Param("id", ParseIntPipe) id: number) {
  return this.users.findOne(id);
}

8. Exception Filter

typescript

Throw a Nest HTTP exception.

if (!user) throw new NotFoundException("User not found");

9. Config Injection

typescript

Read config with ConfigService.

constructor(private readonly config: ConfigService) {}
getPort() {
  return this.config.get<number>("PORT", 3000);
}

10. Async Provider

typescript

Create an async factory provider.

{
  provide: "DB",
  useFactory: async () => connect(),
}

11. Interceptor Logging

typescript

Log request duration with an interceptor.

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    const started = Date.now();
    return next.handle().pipe(tap(() => console.log(Date.now() - started)));
  }
}

12. Dependency Scope

typescript

Inject a request-scoped provider.

@Injectable({ scope: Scope.REQUEST })
export class RequestContext {
  constructor(@Inject(REQUEST) private readonly req: Request) {}
}