---
title: "defineGlobalSingleton"
description: "Define a globalThis singleton keyed by Symbol.for so duplicated bundle copies of a library still share one state."
canonical_url: "https://core.mhaibaraai.cn/en/docs/helpers/define-global-singleton"
---
# defineGlobalSingleton

> Define a globalThis singleton keyed by Symbol.for so duplicated bundle copies of a library still share one state.

## Usage

`defineGlobalSingleton` stores an instance on `globalThis` under `Symbol.for(key)`: the first call runs the factory and later calls return the existing instance. When a library is bundled more than once (for example a Nuxt module and a Vite plugin build), every copy still shares the same state.

```ts
import { defineGlobalSingleton } from '@movk/core'

interface Config {
  token?: string
}

const config = defineGlobalSingleton<Config>('my-lib:config', () => ({}))

export function setToken(token: string) {
  config.token = token
}
```

> [!TIP]
> 
> key
> 
>  is visible across the whole page, so prefix it with your package name (such as 
> 
> 'my-lib:config'
> 
> ) to avoid collisions.

## API

### `defineGlobalSingleton(key, factory)`

Define a cross-copy singleton on `globalThis`.

### Parameters

**key** (`string`) *required*: Globally unique key, turned into a symbol with Symbol.for.

**factory** (`() => T`) *required*: Factory that creates the instance on the first call.

### Returns

**Returns** (`T`): The singleton instance.

## Changelog

See commit history for [src/helpers/defineGlobalSingleton.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/helpers/defineGlobalSingleton.ts).

---

- [GitHub](https://github.com/mhaibaraai/movk-core/blob/main/src/helpers/defineGlobalSingleton.ts)


## Sitemap

See the full [sitemap](https://core.mhaibaraai.cn/sitemap.md) for all pages.
