Heuristic:Openai Openai node Browser Safety Guard
| Knowledge Sources | |
|---|---|
| Domains | Security, Browser |
| Last Updated | 2026-02-15 12:00 GMT |
Overview
Security guard that blocks SDK instantiation in browser environments by default, requiring explicit opt-in via `dangerouslyAllowBrowser: true` to prevent accidental API key exposure.
Description
The SDK detects browser-like environments by checking for the presence of `window`, `window.document`, and `navigator` globals. When detected, it throws an `OpenAIError` unless the developer explicitly sets `dangerouslyAllowBrowser: true`. This prevents the most common security mistake when using the SDK: embedding a secret API key in client-side JavaScript where it can be extracted by anyone inspecting the page source or network traffic.
Usage
This heuristic applies when instantiating the OpenAI client in any environment that resembles a browser (including jsdom test environments). If you need to call the API from the browser, the recommended approach is to create an ephemeral session token server-side and use it client-side, rather than exposing your full API key.
The Insight (Rule of Thumb)
- Action: Never instantiate `new OpenAI({ apiKey })` in browser code with your real API key.
- Value: Set `dangerouslyAllowBrowser: true` only when you have verified that no secret API key is exposed (e.g., using ephemeral tokens or a proxy).
- Trade-off: Disabling the guard enables browser usage but shifts the security burden to the developer.
- For Realtime API: The browser guard also applies to `OpenAIRealtimeWebSocket`. Use ephemeral session tokens created via the server-side Realtime Sessions API.
Reasoning
API keys are bearer tokens with full account access. If embedded in client-side JavaScript, they can be extracted by any user via browser DevTools. The SDK's default-deny approach ensures developers must consciously acknowledge the risk. This is consistent with the OpenAI API key safety best practices documentation.
Code Evidence
Browser detection from `src/internal/detect-platform.ts:5-14`:
export const isRunningInBrowser = () => {
return (
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
typeof navigator !== 'undefined'
);
};
Guard in client constructor from `src/client.ts:400-404`:
if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
throw new Errors.OpenAIError(
"It looks like you're running in a browser-like environment.\n\n" +
"This is disabled by default, as it risks exposing your secret API " +
"credentials to attackers.\nIf you understand the risks and have " +
"appropriate mitigations in place,\nyou can set the " +
"`dangerouslyAllowBrowser` option to `true`, e.g.,\n\n" +
"new OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\n" +
"https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n",
);
}