Check in which environment the code is running

Serhii Shramko /

This snippet shows how to check in which environment the code is running. It's useful when you need to run different code based on the environment, for example, to use different configurations, APIs or Frameworks.

const isBrowser: boolean =
  typeof window !== "undefined" &&
  typeof window.document !== "undefined";
const isNode: boolean =
  typeof process !== "undefined" &&
  process.versions.node != null &&
process.versions != null;
if (isBrowser) {
  // do browser only code
}

if (isNode) {
  // do Node.js only code
}

I have great example where it can be used in my another snippet - Generating UUIDs in JavaScript.