Pattern 05/22 · Creational

Singleton

Guarantee that the whole process has exactly one instance, and expose a single door for getting it. In JS, ES modules already handle the "one instance" part, so the real value of the pattern lies elsewhere: controlling *when* the instance is born, *with which arguments*, and *who is allowed to replace it in tests*.

Creational●○○12 min read8 stepsalso known as: Global Instance, Module Instance
singletonglobal statemodulelazy initdependency injectiontestingcomposition root

01 — It starts with code that is breaking

Problem

You have utils/db.ts: export const prisma = new PrismaClient(). Anyone who needs it does import { prisma }. It works fine for six months. Then you write your first unit test for OrderService.cancel() — and your test connects to the real dev DB, because a bare import runs the module body without asking anyone. To stop that, you add vi.mock("~/utils/db"), and from then on your test behavior depends on a module path as a string: rename the file and the test silently tests something that no longer exists.

Then someone "improves" it to look professional: class DB { private static inst; static get(cfg) { return this.inst ??= new DB(cfg) } }. Clever. And a new bug shows up: getInstance(config) takes an argument, but only the argument from the first call is ever used. File A imports first with the staging DSN, file B imports later with the prod DSN — B silently gets staging. No exception, no warning, no log. The only thing ignored is the argument you thought was taking effect.

On the server it gets worse. You put let currentUser at module scope in a Nuxt server route, set it in middleware, read it in the handler. One request: correct. Two concurrent requests: user A's handler reads the very currentUser that user B's request just overwrote. This is not a performance bug, it is a security bug, and it exists because Node's module scope lives for the whole process, while a request lives for a few dozen ms.

Dev and prod lifecycles differ too. Turn on HMR/nodemon, the module gets re-evaluated, the old client still holds its connection pool while the new client opens another one → you run out of connections (Prisma literally has to recommend stashing the client on globalThis in dev). Serverless is the opposite: the process stays warm and module state survives across invocations, so the Map you put at module scope "as a temporary cache" turns out to be a permanent cache — and if its key lacks a tenant id, it serves one customer's data to another.

The pattern is not the culprit. The culprit is the hidden dependency: the call site does not declare it in its function signature, so you cannot see it when reading code, cannot grep who uses what, cannot swap it in tests, and cannot move it during a refactor. Bottom line: "one instance" is a legitimate requirement; "everyone can grab it from a global" is what makes it expensive.

02 — The idea, before touching code

Solution

The GoF shape: a private constructor so nobody can new it, a static field holding the instance, and a static method getInstance() that creates it if it does not exist yet. In TypeScript those three details are all you need, and they do exactly two things: forbid a second copy, and defer creation until it is actually needed.

But in JS we have to say it plainly: an ES module is already a singleton. The first import runs the module body, the result is stored in the module registry, and every other importer shares that exact object. export const prisma = new PrismaClient() is a Singleton — shorter, typed, and nobody has to remember to call getInstance(). Stacking a class + getInstance on top only buys you one more global access door, which is exactly what we are about to remove.

So the version worth using splits the pattern in two: keep the lifecycle part (one instance, lazy creation, created in exactly one place), drop the global access part (nobody imports it to use on the sly). The instance lives in a module, gets initialized at the composition root — the app entrypoint, a Nuxt plugin, the server entry — and then flows into business code as a parameter. The server still has one pool; tests pass in a fake; and OrderService declares exactly what it needs right in its function signature.

03 — Doing it for real, one code fragment per step

Step by step

1

Write the GoF version first, to see what it actually buys you

private constructor blocks new from outside. A static field holds the instance. getInstance() creates it if missing. Eight lines, and that is everything Singleton gives you.

Write it once to get the full shape, and then we will point out which of these eight lines are redundant in JS.

tsdb-goF.ts
export class DB {
  private static inst: DB | undefined

  private constructor(private readonly dsn: string) {}

  static getInstance(dsn: string): DB {
    this.inst ??= new DB(dsn)
    return this.inst
  }

  query(sql: string) { return this.dsn + ' :: ' + sql }
}

DB.getInstance('dsn://staging')
DB.getInstance('dsn://prod') // <-- this dsn is IGNORED, no error
The last line is the most dangerous one: the API accepts an argument but only trusts the first one.
Key pointSingleton = "no second copy allowed" + "lazy creation". If neither of those is your problem, you do not need this pattern.
2

Say it plainly: an ES module is already a singleton

The JS module registry maps (specifier, realm) → module record. The module body runs once; later imports read from the cache. That means export const x = new Thing() already guarantees "exactly one instance" more strongly than getInstance() does: nobody can create a second one because nobody calls the constructor.

It is also statically typed. DB.getInstance() returns DB because you promised so; import { db } returns DB because the compiler knows.

tslogger.ts
// logger.ts
class Logger {
  private lines: string[] = []
  log(msg: string) { this.lines.push(msg); return this }
  dump() { return this.lines.length }
}
export const logger = new Logger()   // module body runs EXACTLY ONCE

// a.ts:  import { logger } from './logger'   <- first time: run body, store in registry
// b.ts:  import { logger } from './logger'   <- later times: read from registry
// so  l1 === l2  always holds, within the same module record + the same realm.

// What you CANNOT create this way: a second copy. Nobody calls the constructor.
No getInstance class, no hand-rolled registry. The module system already does the "exactly one" part, and it does it with static types rather than a promise.
Key pointWriting a Singleton class on top of export const does not make anything safer — it just adds another path for global access.
3

Go lazy: do not run initialization at import time

export const prisma = new ... has a price: importing means running. In SSR, the bundle loaded to render an /about page opens the connection pool too. Serverless pays extra money and extra cold-start time for something the request does not use. And if another module imports back (circular), it sees a half-initialized module: undefined or a TDZ error at 3 a.m.

This is where Singleton genuinely pays off: getInstance() creates the instance on first use, i.e. after env has been read, config has been validated, and the first request has proven this code needs to run.

tsdb-lazy.ts
class DB {
  private constructor(readonly dsn: string) {}
  private static inst: DB | undefined

  static get(): DB {
    // env is only guaranteed to be readable after the app boots, not at import time
    if (!this.inst) {
      const dsn = process.env.DSN
      if (!dsn) throw new Error('DSN is not configured')
      this.inst = new DB(dsn)
    }
    return this.inst
  }
}

// compare: export const db = new DB(process.env.DSN!)  <- runs immediately on import
export const useDb = () => DB.get()
Going lazy turns "importing has side effects" into "using has side effects", and turns config errors into a named exception instead of a baffling undefined.
Key pointLaziness is not about "optimization": it is how you defer the initialization decision until you have enough information (env, config, the first request).
4

Composition root: one single file knows the init arguments

A Singleton with init arguments needs someone to answer "who passes them, and when". The right answer is: one file — the app entrypoint. A Nuxt plugin, a server/utils/* init, main.ts, or bin/cli.ts. Outside that file, nobody gets to know the DSN, the API key, or the table name.

The corollary: business code must not init. It only gets, and if nothing has been initialized it fails early with a clear message.

tscomposition-root.ts
let db: DB | undefined

/** Only called from the entrypoint / plugin, exactly once. */
export function initDb(config: { dsn: string, pool: number }): void {
  if (db) throw new Error('initDb called twice')
  db = new DB(config.dsn)
}

/** Business code only "gets", never "creates". */
export function getDb(): DB {
  if (!db) throw new Error('initDb has not been called — check the bootstrap plugin')
  return db
}

// nuxt plugin bootstrap.ts: initDb({ dsn: useRuntimeConfig().dbDSN, pool: 5 })
The error message says exactly who got it wrong and where — a far cry from undefined coming out of a module that had not finished initializing.
Key pointAll of the app's wiring should be pushed into one place. If three files each new a shared resource, you do not have a Singleton — you have a race.
5

Cut out the toxic part: turn it into a parameter

This is the one step that turns "a Singleton that is hard to test" into "a safe Singleton". Instead of OrderService doing import { db } itself, it receives db from outside, through the constructor or a factory parameter. The function signature now declares everything it needs — read the signature and you know the dependencies, no need to read the body.

The parameter type should be a small interface (DbClient with just the 2-3 methods the service uses), not a 60-method driver class. A small interface means fakes are easy to write and the driver can be swapped.

tsorder-service.ts
export interface DbClient {
  findOne(sql: string, id: string): Promise<any>
  exec(sql: string, ...args: unknown[]): Promise<void>
}

export function createOrderService(db: DbClient) {
  return {
    async cancel(id: string) {
      await db.exec('update orders set status = $1 where id = $2', 'cancel', id)
    },
  }
}

// The only wiring, at the composition root:
// const orders = createOrderService(getDb())
createOrderService(db) knows nothing about Prisma or Postgres, and imports nothing to use on the sly.
Key pointDI is not a framework. It is "the dependency lives in the function signature, not in the imports of a business file".
6

Test with a fake, drop vi.mock

When the dependency is a parameter, a test only needs an object with the same shape. No mocking by module name, no resetModules(), no worrying about test order, no DB, no Docker. Tests run so fast you actually want to write more of them.

This is where the "classic" Singleton (everyone calls getInstance() themselves) loses most clearly: to test it you have to clean up global state, and once you are cleaning up global state, two tests running in parallel are no longer independent.

tsorder-service.test.ts
interface DbClient {
  exec(sql: string, ...args: unknown[]): Promise<void>
}
const createOrderService = (db: DbClient) => ({
  cancel: (id: string) => db.exec('update orders set status = $1 where id = $2', 'cancel', id),
})

const calls: string[] = []
const fakeDb: DbClient = {
  exec: async (sql, ...args) => { calls.push(sql + ' | ' + args.join(',')) },
}

await createOrderService(fakeDb).cancel('o1')
console.log(calls.join('  ->  '))
// compare with the Singleton version: vi.mock("~/utils/db") + mockReset + worrying about test order
console
update orders set status = $1 where id = $2 | cancel,o1
Key pointIf a test needs to vi.mock a module path just to run, that is a sign the dependency is taking a detour instead of going through the function signature.
7

Never put per-request state at module scope

A hard rule: module scope only holds things that do not change per request (pool, client, clock, logger). Anything that belongs to one request/user — current user, quota, tenant, language, request id — must live in the request object: event.context (Nitro/Nuxt), req.locals (Express), or AsyncLocalStorage.

Same goes for Vue, and the official docs warn about it: a ref() placed at module scope in a composable is shared by every component — handy for global state, but under SSR it is shared across requests, meaning user A gets user B's state. The safe version creates the ref() inside the setup function/composable, or explicitly declares it as intentionally global.

tsper-request.ts
const profile = (user?: string) => 'profile of ' + (user ?? 'UNKNOWN')

// ✗ Wrong: module scope lives for the whole process, requests overlap
let currentUser: string | undefined
async function handlerA(user: string) { currentUser = user; return profile(currentUser) }
async function handlerB() { return profile(currentUser) }   // reads someone else's

;(async () => {
  const p = Promise.all([handlerA('user-A'), handlerB()])
  console.log((await p).join(' | '))
})()

// ✓ Right: state travels with the request object
async function handler(event: { context: any, user: string }) {
  event.context.user = event.user           // Nitro: event.context lives for 1 request
  return profile(event.context.user)
}
console
profile of user-A | profile of user-A
The output line is the proof: handler B returns user A's profile. This kind of bug never shows up when you test one request — it shows up under load, once, in the audit log.
Key pointMaking resources (pool, client) singletons is right. Making the context of a request a singleton is a vulnerability.
8

Check the lifecycle: HMR, warm lambdas, dual packages

Three real things happen to a "single" instance. (1) HMR/nodemon: the module is re-evaluated, a new instance is born, the old one is never closed → the pool balloons; the cure is to conditionally stash the instance on globalThis in dev, which is exactly what Prisma recommends. (2) Warm lambdas: state is not reset between invocations, so a module-scope cache is a real cache — it needs a TTL and a key with enough context (tenant, env). (3) Dual package hazard: a package installed twice (ESM + CJS) means two module records, two "singletons", and a baffling a instanceof B that returns false.

Business code has to defend itself with asserts at init time and by not relying on class identity to drive logic.

tslifecycle.ts
class DB { constructor(readonly dsn: string) {} }

// dev: HMR/nodemon re-evaluates the module, but globalThis is not reset
const isDev = "prerender" !== 'production'
const g = globalThis as unknown as { __db?: DB }
let prodInstance: DB | undefined

function getDb(dsn: string): DB {
  if (isDev) return (g.__db ??= new DB(dsn))     // exactly what Prisma recommends
  return (prodInstance ??= new DB(dsn))
}

console.log('HMR-safe, same instance:', getDb('dsn://a') === getDb('dsn://a'))

// Module-scope cache on the server: the key MUST carry enough context, and must expire
const cacheKey = (tenant: string, id: string) => tenant + ':' + id
console.log('key has enough context:', cacheKey('t1', 'u1') !== cacheKey('t2', 'u1'))
console
HMR-safe, same instance: true
key has enough context: true
??= on globalThis is a Singleton that "lets dev restart". It is also proof that a Singleton can exist purely to fix an environment problem, not a design problem.
Key point"One instance" only holds within one module record and one realm. Dev, serverless and duplicated node_modules are three places where that assumption breaks.

04 — Who talks to whom

Structure

  • SingletonClass holding a static field + `getInstance()`. The constructor is private, so `new` from outside is a compile error.
  • InstanceExactly one object living for the lifetime of the module/process: pool, client, reporter, clock.
  • CompositionRootThe entrypoint (Nuxt plugin, server entry, main.ts) that initializes the instance with real config and passes it down.
  • ClientBusiness code. Receives the instance **as a parameter**, never imports it to fetch on its own.
  • TestDoubleA fake with the same interface, passed in exactly where the Client receives it — instead of mocking by module name.
   ✗ The common version (hidden dependency)
   ┌───────────────────────────────────────────┐
   │ OrderService  ──import──►  utils/db.ts    │  importing in a test
   │ CartService   ──import──►  (new Client)   │  hits the real DB
   └───────────────────────────────────────────┘

   ✓ Keep the lifecycle, drop global access

   Composition root (plugin / entry)
        │  initDb(config)         lazy, exactly once
        ▼
   ┌────────────────────┐   private constructor
   │ module "db"        │   ┌──────────────────────┐
   │  let db: DB        │──►│ DB instance (1)      │
   │  initDb()  getDb() │   └──────────────────────┘
   └─────────┬──────────┘
             │ createOrderService(db)   ← dependency lives in the signature
             ▼
   ┌──────────────────────────────┐
   │ OrderService(db: DbClient)   │  test: createOrderService(fakeDb)
   └──────────────────────────────┘

05 — Edit freely, run it right here

Try it: a controlled singleton, a fake for tests, and per-request state

tsdemo.ts
interface KV {
  get(k: string): string
  set(k: string, v: string): void
}
class Store implements KV {
  static created = 0
  private m = new Map<string, string>()
  constructor() { Store.created++ }
  get(k: string) { return this.m.get(k) ?? '<null>' }
  set(k: string, v: string) { this.m.set(k, v) }
}

// getInstance: create on first call, return the same object afterwards
class Registry {
  private static self: Store | undefined
  static get(): Store {
    if (!Registry.self) Registry.self = new Store()
    return Registry.self
  }
}

Registry.get().set('a', '1')
console.log('1 same object =', Registry.get() === Registry.get(), '| Stores created =', Store.created)

// Dependency Injection: the function receives a KV, it does not fetch the singleton itself
const dump = (kv: KV, keys: string[]) => keys.map(k => k + '=' + kv.get(k)).join(' ')
const store = Registry.get()
store.set('b', '2')
console.log('2 prod        :', dump(store, ['a', 'b']))

// Test fake: the singleton becomes an argument -> tests do not have to clean global state
const fake: KV = { get: k => 'FAKE:' + k, set: () => {} }
console.log('3 test fake   :', dump(fake, ['a', 'b']))

// Server: the module lives for the whole process -> state must be created per request
const perRequest = () => { const s = new Store(); s.set('user', 'u'); return s.get('user') }
console.log('4 per-request :', perRequest(), perRequest(), '| total Stores created =', Store.created)
console
1 same object = true | Stores created = 1
2 prod        : a=1 b=2
3 test fake   : a=FAKE:a b=FAKE:b
4 per-request : u u | total Stores created = 3

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • Resources that are expensive to create and benefit from sharing: DB pool, driver, WebSocket connection, an authenticated SDK client, thread/worker pool.
  • Resources that may only exist once by their semantics: one AudioContext per tab, one ID sequence generator, one reporter batching metrics, one console writer so log lines do not interleave.
  • You need laziness: initialization is expensive or depends on config, and the app can run all day without touching it (admin, export, payment).
  • You need a single initialization point to control the lifecycle: enable/disable, change config at boot, shut down gracefully when the process receives SIGTERM.
  • Browser: you genuinely have only one document, one localStorage, one performance — Singleton there is an objective fact, not a choice.

Don't use it when

  • Hidden dependencies are the real cost: callers do not declare them in their signatures, so reading the code does not reveal them, grep does not find them, swapping the implementation means editing every import site, and moving the module into another package becomes a construction project.
  • Tests: a long-lived instance makes tests order-dependent — test A writes, test B reads A's data. You will add reset()/clearCache() "just for tests", which means opening yet another door that breaks encapsulation. Fix it with DI + fakes, not with --isolated.
  • Server: module scope is shared by every request in the same process. Per-request state (user, tenant, quota, language) placed there leaks data between users; a module-scope cache without a TTL is a slow OOM. Serverless makes both harder to spot because warm processes are unpredictable.
  • getInstance(config) silently ignores the config on the second call. If two legitimate callers can ask for different configs, that is not a Singleton — it is a Factory, and you are hiding a bug behind a pattern.
  • Over-engineering: export const config = loadConfig() is already a Singleton. Do not build class Config { static getInstance() } for completeness — you are only adding a global accessor. Likewise, do not DI-ify a pure 5-line function with no I/O: DI buys testability/swappability, not design points.
  • Two module records means two "singletons" (dual ESM/CJS package, two copies in node_modules, workers in the same realm). instanceof and identity-keyed Maps start getting it wrong. Rely on interfaces, not class identity, to branch.

07 — You have met it already, just not by name

In real code

Prisma client singleton (official recommendation)

Prisma's docs recommend creating one PrismaClient and exporting it, and in dev stashing it on globalThis because nodemon/ts-node-dev re-evaluate the module and the connection pool grows until it hits the limit. That is Singleton exactly, and also exactly the "dev lifecycle differs from prod" example.

axios default export

import axios from "axios" gives you a shared instance. axios.defaults.headers.common.Authorization = ... affects every call in the process — dangerously convenient. That is why the docs always recommend axios.create(...) when you need your own config: escaping the Singleton once the Singleton has become global mutable state.

Vue composables: ref() at module scope

The Vue docs ("Sharing Composables State") show exactly this pattern: a ref() placed outside the function means every component shares the state. With an SSR warning: that state is shared across requests, so the safe code creates the ref() inside the composable. Singleton is something you choose deliberately, not a default.

Nuxt/Nitro server: event.context and useRuntimeConfig

Nitro keeps heavy things (driver, pool) at module scope to reuse across requests, but everything that belongs to one request must live in event.context; useRuntimeConfig() is the config singleton, read at boot. Respect this boundary and HMR does not break anything; get it wrong and data leaks between users.

Browser: AudioContext, localStorage, performance

The environment only provides one of each, so audio libs keep exactly one AudioContext in their module (browsers cap the number of concurrent contexts and will warn you). navigator.clipboard and window.matchMedia are one-of-a-kind too — Singleton is not a choice here, it is the platform's contract.

08 — Try it yourself

Exercise

`orderService.ts` does `import { db } from "~/utils/db"` and then calls `db.exec(...)`; its test requires `vi.mock("~/utils/db")` and often fails when the whole file runs. Refactor: the service receives its dependency as a parameter with a minimal interface, keep the real instance from the composition root as the **default**, then rewrite the test using a fake without mocking any module.

Hints, open them one at a time:

  1. List exactly what the service calls on db — usually just 2 methods. Declare interface DbClient with exactly those 2 methods (interface segregation, and the fake gets much shorter).
  2. Move from class OrderService + import to function createOrderService(db: DbClient). If you want "anyone can call it without passing anything", give the parameter a default: db = getDb(). Default wiring in production, tests pass a fake.
  3. Test: set up const calls: string[] = [], make the fake exec just push into calls, then assert on calls. If you still need vi.mock, something somewhere is still importing it to use on the sly.

Extract a small interface, move the dependency into the factory function's parameter, keep getDb() as the default for production. Production changes not a single line of wiring; the test loses all its mocks and its dependency on run order.

tsexercise.ts
// db.ts — the composition root owns the "one instance" part
export interface DbClient {
  exec(sql: string, ...args: unknown[]): Promise<void>
}
let real: DbClient | undefined
export function initDb(client: DbClient): void {
  if (real) throw new Error('initDb called twice')
  real = client
}
export function getDb(): DbClient {
  if (!real) throw new Error('initDb has not been called')
  return real
}

// order-service.ts — imports nothing to use on the sly (reads DbClient/getDb from db.ts)
export const createOrderService = (db: DbClient = getDb()) => ({
  async cancel(id: string) {
    await db.exec('update orders set status = $1 where id = $2', 'cancel', id)
  },
})

// test — no vi.mock, no reset, runs in isolation
const calls: string[] = []
const fake: DbClient = { exec: async (sql, ...a) => { calls.push(sql + ' [' + a.join(',') + ']') } }

await createOrderService(fake).cancel('o1')   // test: pass the dependency yourself
initDb(fake)                                  // wiring: exactly ONCE, at the entry
await createOrderService().cancel('o2')       // nothing passed -> falls back to getDb()

console.log('commands recorded:', calls.length, '| single instance:', getDb() === getDb())

09 — Read them in pairs to see the essence

Related patterns

  • FacadeThey pair up a lot: a singleton module usually comes with a few easy exported functions, which makes it a Facade. Facade handles "an API that is easy to call", Singleton handles "exactly one instance" — two different problems, do not mix them up.
  • FlyweightBoth are about "sharing instances", but Flyweight shares **many** small objects with immutable shared state, while Singleton shares **one** object for its whole life. Flyweight optimizes memory; Singleton manages lifecycle.
  • ProxyA Proxy is the natural place to wrap a lazy singleton: `getInstance()` inside the handler, so the real instance is only created on the first call. Virtual Proxy and lazy Singleton differ mostly in name.
  • Abstract FactoryAbstract Factory picks a **family** of objects by environment (dev/test/prod), Singleton decides that whatever was picked exists **once**. This pair shows up often: a real driver for prod, a fake driver for test, one instance each.