10 / 11

What is the difference between useExisting and useClass when aliasing a provider in NestJS?

useClass with a class always creates a new independent instance managed by the container. useExisting resolves and returns the same singleton instance of the referenced token — no new instantiation occurs. Use useExisting when you need backward-compatible aliases without duplicating state.

useClass vs useExisting — instance behavior
When to use each:
  1. 1

    useClass — when you want an independent instance with its own state.

  2. 2

    useExisting — when you want two token names to point to the exact same runtime object.

  3. 3

    useExisting is useful for maintaining backward-compatible tokens in evolving APIs.

  4. 4

    useExisting requires the referenced token to already be registered in the same module or an imported module.