What is dependency injection in Node.js?
Answer
Dependency injection (DI) is a design pattern where a module's dependencies are provided (injected) from the outside rather than created internally. This decouples components, making them individually testable and interchangeable. Without DI: class UserService { constructor() { this.db = new Database(); } } — UserService is tightly coupled to a specific Database implementation, making it hard to test or swap. With DI: class UserService { constructor(db) { this.db = db; } } — the database is injected, so tests can pass a mock. In plain Node.js/Express, manual DI is common: create dependencies in one place and pass them to service constructors. DI containers (IoC containers) automate this: InversifyJS (decorator-based DI container), Awilix (simple, lightweight), NestJS (has DI built-in as a core feature, similar to Angular's DI system). DI is fundamental to writing SOLID code, particularly the Dependency Inversion Principle.
Previous
What is Helmet.js and why should you use it?
Next
How do you write unit tests for Node.js applications?