0
0
NestJSframework~3 mins

Why Injectable decorator in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple decorator can save you from tangled, buggy code!

The Scenario

Imagine building a large app where you have to create and manage every service and its dependencies by hand.

Every time you want to use a service inside another, you must manually create instances and pass them around.

The Problem

This manual approach quickly becomes messy and error-prone.

You might accidentally create multiple instances of the same service, causing inconsistent data.

It's hard to track who needs what, and changing one service means updating many places.

The Solution

The Injectable decorator in NestJS marks a class as a service that can be automatically created and shared.

It lets NestJS handle creating and providing the right instances wherever needed.

This makes your code cleaner, easier to maintain, and less buggy.

Before vs After
Before
const service = new Service();
const controller = new Controller(service);
After
@Injectable()
class Service {}

@Injectable()
class Controller {
  constructor(private readonly service: Service) {}
}
What It Enables

It enables automatic and consistent sharing of services across your app without manual wiring.

Real Life Example

Think of a user authentication service that many parts of your app need.

With @Injectable(), you write it once, and NestJS provides the same instance everywhere it's needed.

Key Takeaways

Manually managing service instances is hard and error-prone.

@Injectable() marks classes for automatic creation and sharing.

This leads to cleaner, more maintainable, and reliable code.