---
id: wiki-2026-0508-nodejs-global-namespace-augmenta
title: Node.js Global Namespace Augmentation
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Node.js Global Augmentation, globalThis Augmentation, Node Global Types]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [nodejs, typescript, declaration-merging, global, types]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: TypeScript
  framework: Node.js
---

# Node.js Global Namespace Augmentation

## 매 한 줄
> **"매 globalThis 의 typed extension"**. Node.js 환경에서 매 global / globalThis 에 property 추가 시 (e.g. dev-mode singleton, env-typed config, monkey-patch), TS declaration merging 으로 매 type-safe access. 매 `declare global { ... }` + module file (top-level import/export) 매 정답.

## 매 핵심

### 매 왜 필요
- Dev hot-reload 의 Prisma/Mongoose client singleton 매 module-level 으로는 reload 마다 reconnect.
- `process.env` 의 strict typing.
- Vitest/Jest setup 의 global helper.
- Polyfill / shim 매 global 추가.

### 매 globalThis vs global vs window
- **globalThis**: 매 모든 환경 (Node, browser, worker) — 매 prefer.
- **global**: Node.js 만 — 매 deprecated trend.
- **window**: 매 browser only.

### 매 응용
1. Prisma / DB client dev-singleton.
2. Typed `process.env` (NODE_ENV, DATABASE_URL).
3. Test setup global mocks.
4. Monkey-patched `fetch` / `Buffer`.

## 💻 패턴

### globalThis singleton (매 Prisma dev)
```ts
// db.ts
import { PrismaClient } from "@prisma/client";

declare global {
  // eslint-disable-next-line no-var
  var __prisma: PrismaClient | undefined;
}

export const prisma = globalThis.__prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== "production") {
  globalThis.__prisma = prisma;
}
```

### Typed process.env
```ts
// env.d.ts
declare namespace NodeJS {
  interface ProcessEnv {
    readonly NODE_ENV: "development" | "production" | "test";
    readonly DATABASE_URL: string;
    readonly OPENAI_API_KEY: string;
    readonly LOG_LEVEL?: "debug" | "info" | "warn" | "error";
  }
}
export {};
```

### Augment global with custom helper
```ts
// global.d.ts
declare global {
  function inject<T>(token: string): T;
  var __APP_VERSION__: string;
}
export {};

// runtime.ts
globalThis.inject = function <T>(token: string): T { /* ... */ return null as any; };
globalThis.__APP_VERSION__ = "1.4.2";
```

### Test setup augmentation (Vitest)
```ts
// vitest.setup.ts
import { vi } from "vitest";

declare global {
  var fetchMock: ReturnType<typeof vi.fn>;
}

globalThis.fetchMock = vi.fn();
globalThis.fetch = globalThis.fetchMock as any;
```

### Monkey-patch with type
```ts
// fetch-with-retry.ts
declare global {
  interface GlobalThis {
    originalFetch?: typeof fetch;
  }
}

if (!globalThis.originalFetch) {
  globalThis.originalFetch = globalThis.fetch;
  globalThis.fetch = async (input, init) => {
    for (let i = 0; i < 3; i++) {
      try {
        return await globalThis.originalFetch!(input, init);
      } catch (e) {
        if (i === 2) throw e;
        await new Promise(r => setTimeout(r, 100 * 2 ** i));
      }
    }
    throw new Error("unreachable");
  };
}
```

### Validated env (Zod)
```ts
import { z } from "zod";

const envSchema = z.object({
  NODE_ENV: z.enum(["development", "production", "test"]),
  DATABASE_URL: z.string().url(),
  PORT: z.coerce.number().default(3000),
});

export const env = envSchema.parse(process.env);
// env.PORT: number, env.DATABASE_URL: string
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| Dev singleton | globalThis cache + declare global |
| Env typing | namespace NodeJS.ProcessEnv (or Zod) |
| Test mocks | declare global in setup |
| Runtime validation | Zod / Valibot — 매 declare 만 매 trust X |
| Module-scoped state | normal module export, not global |

**기본값**: 매 globalThis + `declare global { var ... }` (top-level export 로 module 화).

## 🔗 Graph

## 🤖 LLM 활용
**언제**: dev singleton, typed env, test global mock, runtime polyfill.
**언제 X**: app state 의 global stash — 매 anti-pattern. Module export 로 한정.

## ❌ 안티패턴
- **No `export {}`**: 매 d.ts 가 module 인식 X — 매 global pollute or merge 실패.
- **`global.x = ...` without declare**: 매 TS error or any.
- **Production singleton on global**: 매 cluster mode worker 별 다른 instance.
- **Trust env type only**: 매 runtime validation 없이 매 typo 매 silent undefined.
- **Mutate built-ins**: 매 `Array.prototype` 매 augment — library 호환성 폭망.

## 🧪 검증 / 중복
- Verified (TypeScript Handbook — Declaration Merging, Node.js docs globalThis, Prisma docs Best Practices).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Prisma singleton, ProcessEnv, Zod env, monkey-patch 패턴 |
