v2.0.0

Environment

Runtime environment detection — getEnvironment() and the Environment enum for branching between browser and Node.js code paths.

Overview

getEnvironment() reports whether the code is running in a browser, in Node.js, or in an environment the SDK cannot classify. It returns a member of the Environment enum. Both are exported from @bitrix24/b24jssdk and are used internally to gate browser-only behaviour (DOM, localStorage, iframe messaging) away from server contexts.

import { getEnvironment, Environment } from '@bitrix24/b24jssdk'

if (getEnvironment() === Environment.BROWSE) {
  // browser-only code (DOM, localStorage, …)
}

Method Signature

enum Environment {
  UNKNOWN = 'unknown',
  BROWSE = 'browser',
  NODE = 'node'
}

getEnvironment(): Environment

Key Concepts

  • Detection order. getEnvironment() first checks for a browser by testing window and window.document; if both are present it returns Environment.BROWSE. Otherwise it checks for Node.js via process.versions.node; if present it returns Environment.NODE. When neither matches it returns Environment.UNKNOWN.
  • The browser member is BROWSE, its value is 'browser'. Compare against the enum member (Environment.BROWSE), not a bare string, so a rename stays type-safe.
  • UNKNOWN covers everything else. Web workers, edge/serverless runtimes, and other hosts without a DOM window or a Node process fall through to Environment.UNKNOWN — treat it as "assume no browser globals".

Error Handling

getEnvironment() never throws. Every check uses typeof guards, so a missing window or process degrades to the next branch rather than raising a ReferenceError.

Examples

Branch between browser and Node.js:

import { getEnvironment, Environment } from '@bitrix24/b24jssdk'

switch (getEnvironment()) {
  case Environment.BROWSE:
    // Safe to touch the DOM / localStorage here
    break
  case Environment.NODE:
    // Server-side path (e.g. read env vars, use a webhook client)
    break
  default:
    // Environment.UNKNOWN — avoid browser and Node-specific globals
    break
}

Guard browser-only work before it runs:

import { getEnvironment, Environment } from '@bitrix24/b24jssdk'

function isBrowser(): boolean {
  return getEnvironment() === Environment.BROWSE
}

if (isBrowser()) {
  // window / document are available
}

Alternatives and Recommendations

  • Use getEnvironment() for a coarse "where am I running" branch. For finer browser/OS/capability checks (Chrome vs Safari, iOS, touch, localStorage availability) use Browser instead.
  • Prefer it over ad-hoc typeof window checks. Centralising the detection keeps browser/Node branching consistent and matches the checks the SDK itself makes internally.
  • Treat UNKNOWN conservatively. When you cannot confirm a browser, avoid DOM and localStorage access — many Browser methods assume those globals exist and can throw outside a browser.