0
0
NestJSframework~5 mins

Provider scope (default, request, transient) in NestJS

Choose your learning style9 modes available
Introduction

Provider scope controls how NestJS creates and shares service instances. It helps manage when and how often a service is created.

When you want a single shared service instance for the whole app (default scope).
When you need a new service instance for each incoming request (request scope).
When you want a new service instance every time it is injected (transient scope).
Syntax
NestJS
import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.DEFAULT })
export class MyService {}

Use Scope.DEFAULT for a singleton service shared app-wide.

Use Scope.REQUEST to create a new instance per HTTP request.

Examples
This service uses the default singleton scope.
NestJS
import { Injectable, Scope } from '@nestjs/common';

@Injectable()
export class DefaultService {}
This service creates a new instance for each request.
NestJS
import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class RequestService {}
This service creates a new instance every time it is injected.
NestJS
import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.TRANSIENT })
export class TransientService {}
Sample Program

This example shows a request-scoped service that generates a random ID when created. Each HTTP request gets a new service instance with a different ID.

NestJS
import { Injectable, Scope, Controller, Get } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class RequestScopedService {
  private readonly id: number;

  constructor() {
    this.id = Math.floor(Math.random() * 1000);
  }

  getId() {
    return this.id;
  }
}

@Controller()
export class AppController {
  constructor(private readonly requestService: RequestScopedService) {}

  @Get()
  getId() {
    return `RequestScopedService ID: ${this.requestService.getId()}`;
  }
}
OutputSuccess
Important Notes

Default scope means one instance shared everywhere.

Request scope is useful for services that hold request-specific data.

Transient scope creates a fresh instance every time, useful for stateless helpers.

Summary

Provider scope controls service instance lifetime in NestJS.

Default scope shares one instance app-wide.

Request scope creates a new instance per HTTP request.

Transient scope creates a new instance every injection.