Back to results for “Design Patterns in JavaScript”
Node.js › Architecture & Design Patterns

What is the Singleton pattern, and what are the specific risks of using it in a Node.js application?

Intermediate

Answer

A Singleton ensures only one instance of a class or module-level object exists and is shared across the entire application -- in Node.js this is trivially achieved because a required module is cached and reused by reference after its first load, so a module that exports a single instantiated object naturally behaves as a singleton. The main risk is that singletons introduce hidden global state, making unit tests harder to isolate (state can leak between tests) and creating implicit coupling between unrelated parts of the codebase that all depend on the same shared instance.
// database.js -- naturally a singleton due to module caching
class Database {
  constructor() { this.connection = connectToDb(); }
}
module.exports = new Database(); // same instance returned on every require()
Real-world example A connection-pool manager is implemented as a module-level singleton so that every part of an application shares the same underlying pool of database connections, but this later complicates testing until the team refactors to inject the pool explicitly rather than importing the singleton directly.

Common follow-ups: How would you refactor a singleton-based module to be more testable via dependency injection?;What happens to a 'singleton' module if it's required from two different node_modules copies of the same package?