# Providers & Services — NestJS: Building Scalable Node.js APIs

Source: https://www.skillbyai.com/en/nestjs/nestjs-providers-services

> Put business logic in @Injectable services, register them as providers and export them to other modules.

## Anatomy of a service

A service is a class with `@Injectable()` that holds your business logic—fetching data, validating rules, etc.

```typescript
import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  private users = [];

  findAll() {
    return this.users;
  }

  create(user) {
    this.users.push(user);
    return user;
  }
}
```

## Providers in modules

Register services in the `providers` array of a module; also `export` them if other modules need them.

## Custom providers with useValue

For constants or mocks use `{ provide: 'API_KEY', useValue: 'abc' }` and inject it with `@Inject('API_KEY')`. Strings need `@Inject` because they have no runtime type.

Quick check

**Quiz:** What is the default scope of a Nest provider?

- [ ] A new instance per request
- [ ] A new instance per injection
- [x] A single shared instance (singleton)

*Answer:* A single shared instance (singleton). By default Nest creates one instance and reuses it. Request scope must be opted into.
