Skip to content
jshacks.dev
Patterns

How to Structure Dependency Injection in NestJS

Learn how to structure dependency injection in NestJS 11: providers, modules, custom tokens, scopes, circular dependencies and tests with overrideProvider.

8 min read
Summarize in AI
Flat illustration of a service container binding interfaces to classes, with the JavaScript, React and TypeScript logos.

NestJS is built around dependency injection. Classes marked @Injectable() are providers, modules group providers and decide what they expose, and the framework's container builds the graph and passes each provider what its constructor asks for. Getting the structure right, which providers live in which module, what a module exports and when to use a custom token, is what keeps a Nest application maintainable as it grows. This guide covers NestJS 11 on Node.js 24 with TypeScript 5.9: providers and modules, injecting interfaces with tokens, useClass, useValue and useFactory, scopes, circular dependencies, dynamic modules and tests with overrideProvider.

The pieces

A provider is any class the container manages: services, repositories, factories and helpers. It is marked with @Injectable() and listed in a module's providers array.

A module is a class marked with @Module() that groups related providers and controllers. Each module has a private scope: its providers are visible only inside it unless the module exports them, and other modules must import it to use them.

The container is built when the application starts. It reads the modules, creates providers in dependency order and keeps singletons.

This structure forces an explicit answer to "who can use what", which is the most useful property of Nest's design. A provider that is not exported cannot be reached from outside, so each module has a public surface and a private interior.

Step 1: a provider with a dependency

A service injects another provider through its constructor. Nest reads the parameter types from emitted metadata, so no @Inject is needed for class types.

users.service.tsTypeScript
import { Injectable } from "@nestjs/common";

@Injectable()
export class UsersRepository {
  private readonly users = new Map<number, string>([[1, "Ada"], [2, "Lin"]]);

  findName(id: number): string | undefined {
    return this.users.get(id);
  }
}

@Injectable()
export class UsersService {
  constructor(private readonly repository: UsersRepository) {}

  greet(id: number): string {
    return `Hello, ${this.repository.findName(id) ?? "stranger"}`;
  }
}

Nest relies on experimentalDecorators and emitDecoratorMetadata, which the project template enables, so the usual way to run it is nest start or a build with the Nest CLI. Imports in Nest projects are written without file extensions, as in the examples below.

Step 2: a module that owns them

The module lists its providers and exports what the rest of the application may use.

users.module.tsTypeScript
import { Module } from "@nestjs/common";
import { UsersRepository, UsersService } from "./users.service";

@Module({
  providers: [UsersRepository, UsersService],
  exports: [UsersService],
})
export class UsersModule {}

UsersRepository is not exported, so other modules cannot inject it. They can only use UsersService, which is the intended public API. If another team wants to read users, they go through the service, and the repository can change without breaking anyone.

Step 3: another module imports it

app.module.tsTypeScript
import { Module } from "@nestjs/common";
import { UsersModule } from "./users.module";

@Module({
  imports: [UsersModule],
})
export class AppModule {}
main.tsTypeScript
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { UsersService } from "./users.service";

async function bootstrap() {
  const app = await NestFactory.createApplicationContext(AppModule, { logger: false });
  const users = app.get(UsersService);

  console.log(users.greet(1));
  console.log(users.greet(9));
  await app.close();
}

void bootstrap();
Text
Hello, Ada
Hello, stranger

createApplicationContext builds the container without starting an HTTP server, which is useful for scripts, workers and tests. app.get(UsersService) looks the provider up, finding it through the exported surface of UsersModule. In a real application, a controller declares UsersService in its constructor and Nest injects it, and NestFactory.create starts the server.

Injecting interfaces and values with tokens

An interface has no run-time representation, so Nest cannot inject by its type. Provide it under a token and inject with @Inject(token). A string or a Symbol both work, and a constant keeps them consistent.

mail.tsTypeScript
import { Inject, Injectable, Module } from "@nestjs/common";

export interface Mailer {
  send(to: string, text: string): string;
}

export const MAILER = Symbol("MAILER");

@Injectable()
class SmtpMailer implements Mailer {
  send(to: string, text: string): string {
    return `smtp -> ${to}: ${text}`;
  }
}

@Injectable()
export class WelcomeService {
  constructor(@Inject(MAILER) private readonly mailer: Mailer) {}

  welcome(email: string): string {
    return this.mailer.send(email, "Welcome");
  }
}

@Module({
  providers: [
    { provide: MAILER, useClass: SmtpMailer },
    WelcomeService,
  ],
  exports: [WelcomeService],
})
export class MailModule {}

The custom provider { provide: MAILER, useClass: SmtpMailer } says: when something asks for MAILER, build SmtpMailer. The consumer depends on the Mailer interface and the token, and has no idea which class answers. Changing the implementation is a change to the module's provider list.

There are four ways to define a custom provider.

FormMeaning
useClassConstruct this class when asked for the token
useValueUse this existing value, such as configuration or a fake
useFactoryCall this function to build the value, with inject listing its dependencies
useExistingMake the token an alias of another provider
providers.tsTypeScript
import { Module } from "@nestjs/common";

export const API_URL = "API_URL";
export const ENDPOINT = "ENDPOINT";

@Module({
  providers: [
    { provide: API_URL, useValue: "https://api.example.com" },
    {
      provide: ENDPOINT,
      useFactory: (apiUrl: string) => `${apiUrl}/v1`,
      inject: [API_URL],
    },
  ],
  exports: [ENDPOINT],
})
export class ConfigModule {}

A factory lists its dependencies in inject, in the order of its parameters, and Nest passes them in. A factory may also be asynchronous, returning a promise: Nest waits for it before creating the providers that depend on it, which is the standard way to open a database connection at startup.

Scopes

By default a provider is a singleton: one instance for the application's life. Two other scopes exist.

scopes.tsTypeScript
import { Injectable, Scope } from "@nestjs/common";

@Injectable()
export class SingletonService {}

@Injectable({ scope: Scope.REQUEST })
export class RequestContextService {}

@Injectable({ scope: Scope.TRANSIENT })
export class TransientHelper {}

Scope.REQUEST creates a new instance per incoming request and discards it after. Scope.TRANSIENT creates a new instance for each consumer that injects it. A request-scoped provider makes everything that depends on it request-scoped as well, up the chain, including controllers, and creating those objects on each request has a cost. Use request scope when you truly need per-request state, such as the current tenant, and prefer passing values explicitly, or AsyncLocalStorage-based solutions, for the rest. Nest's documentation states the same caution.

Circular dependencies

If A injects B and B injects A, Nest cannot construct either first. The framework offers forwardRef as an escape hatch.

circular.tsTypeScript
import { forwardRef, Inject, Injectable } from "@nestjs/common";

@Injectable()
export class OrdersService {
  constructor(
    @Inject(forwardRef(() => InvoicesService))
    private readonly invoices: InvoicesService,
  ) {}
}

@Injectable()
export class InvoicesService {
  constructor(
    @Inject(forwardRef(() => OrdersService))
    private readonly orders: OrdersService,
  ) {}
}

This works and is a design smell. Two services that need each other usually share a concept that deserves its own provider, so the better fix is to extract the shared part into a third service that both depend on. Treat forwardRef as a way to ship while you refactor, and not as a permanent solution. A cycle between modules, and not only between providers, needs the same forwardRef treatment in the imports array and deserves the same scrutiny.

Dynamic modules for configuration

A module often needs configuration from the importer. The convention is a static forRoot method that returns a dynamic module with providers built from the options.

dynamic.tsTypeScript
import { DynamicModule, Module } from "@nestjs/common";

export const GREETING = "GREETING";

@Module({})
export class GreetingModule {
  static forRoot(options: { greeting: string }): DynamicModule {
    return {
      module: GreetingModule,
      providers: [{ provide: GREETING, useValue: options.greeting }],
      exports: [GREETING],
    };
  }
}

The importer writes GreetingModule.forRoot({ greeting: "Hi" }) in its imports. This is how ConfigModule.forRoot() and TypeOrmModule.forRoot() are built. For modules that need asynchronous configuration, the matching convention is forRootAsync with a factory.

Structuring a growing application

A few rules keep the module graph healthy.

One module per feature. UsersModule, OrdersModule and BillingModule each own their providers and controllers. A "shared" module that holds unrelated utilities becomes a dumping ground.

Export services, not repositories. Export the narrow public API of the feature, and keep data access private. Other modules ask the service.

Depend downward. Feature modules depend on infrastructure modules, such as database and configuration, and not the other way around. A diagram of imports with no arrows pointing back up is a sign of a clean structure.

**Use @Global() rarely.** A global module is visible everywhere without being imported. It suits truly application-wide services, such as configuration or logging, and hides dependencies if overused.

Keep controllers thin. A controller maps HTTP to a service call. The service holds logic and depends on repositories and other services.

Tests with overrideProvider

Nest's testing package builds a module in a test, and lets you replace providers.

users.service.test.tsTypeScript
import { Test } from "@nestjs/testing";
import assert from "node:assert/strict";
import { test } from "node:test";
import { UsersModule } from "./users.module";
import { UsersRepository, UsersService } from "./users.service";

test("greet uses the repository result", async () => {
  const moduleRef = await Test.createTestingModule({ imports: [UsersModule] })
    .overrideProvider(UsersRepository)
    .useValue({ findName: () => "Grace" })
    .compile();

  const service = moduleRef.get(UsersService);
  assert.equal(service.greet(1), "Hello, Grace");
});
Text
✔ greet uses the repository result (14.8ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

The real UsersModule was built, with its repository replaced by a stub, so the test covers the real wiring of UsersService. overrideProvider accepts useValue, useClass and useFactory. For fast unit tests of one class, you can also skip the module entirely and construct it with new UsersService(fakeRepository), since constructor injection is plain TypeScript. Use the testing module when wiring is part of what you want to check.

Pitfalls

**Provider not in providers.** The error is Nest can't resolve dependencies of the X (?), naming the position of the unresolved parameter. Add the provider to the module, or import the module that exports it.

Provider not exported. The same error appears when a provider exists but sits in another module that does not export it. Add it to exports.

**Forgetting @Inject for tokens.** A parameter typed as an interface is emitted as Object. Always add @Inject(TOKEN) for custom tokens.

Request scope spreading. One request-scoped provider can turn half the application into per-request objects. Check what depends on it.

Heavy work in constructors. Constructors run during startup, and Nest does not await them. Use onModuleInit for asynchronous setup, or an async factory provider.

Also inFrameworks
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.