What is dependency injection in Node.js?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
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.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last Node.js project, I used this when...' immediately makes your answer more credible and memorable.
Previous
What is Helmet.js and why should you use it?
Next
How do you write unit tests for Node.js applications?