Js singleton pattern

From Intense-Visions/harness-engineering · View interactive version

Js singleton pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Ensure a class has only one instance and provide a global access point

How to use this skill

Skill file

JS Singleton Pattern

Ensure a class has only one instance and provide a global access point

When to Use

Instructions

  1. Create a class with a private constructor and a static instance variable.
  2. Add a static getInstance() method that returns the existing instance or creates one on first call.
  3. Export only getInstance(), not the class itself.
  4. In ESM modules, prefer a module-level variable over a class — a module is already a singleton by the loader.
// Preferred ESM approach — module-level singleton
let instance;

class DatabaseConnection {
  constructor(url) {
    if (instance) return instance;
    this.url = url;
    this.connected = false;
    instance = this;
  }

  connect() {
    this.connected = true;
  }
}

export const getInstance = (url) => new DatabaseConnection(url);
  1. Freeze the instance with Object.freeze(instance) if it should be immutable after creation.
  2. Avoid singletons for anything that varies per request in server-side code.

Details

The Singleton pattern is one of the most debated patterns in JavaScript. The classic implementation uses a class with a static instance, but ES modules provide a simpler alternative: any module-level variable is effectively a singleton because Node.js and browsers cache module exports after the first import.

Trade-offs:

When NOT to use:

Related patterns:

Source

https://patterns.dev/javascript/singleton-pattern

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.