Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isNode

Determines if the current environment is Node.js.

TypeScript
Copied!
1/**
2 * Determines if the current environment is Node.js.
3 *
4 * @returns True if running in Node.js, false otherwise.
5 */
6export function isNode(): boolean {
7  return (
8    typeof process !== 'undefined' &&
9    !!process.versions?.node &&
10    typeof window === 'undefined'
11  );
12}
  • Accurate Node.js Detection

    Combines multiple checks (process.versions.node and absence of window) to reliably distinguish Node.js from browser and hybrid environments.

  • Avoids False Positives

    Prevents misidentification in environments like Electron or serverless runtimes that may partially expose process or window.

  • Lightweight and Synchronous

    Uses simple, synchronous type checks without any performance cost or external dependencies.

Tests | Examples

TypeScript
Copied!
1const originalProcess = global.process;
2const originalWindow = global.window;
3
4afterEach(() => {
5  global.process = originalProcess;
6  global.window = originalWindow;
7});
8
9test('returns true in Node-like environment', () => {
10  // @ts-ignore
11  global.process = { versions: { node: '20.0.0' } };
12  // @ts-ignore
13  delete global.window;
14  expect(isNode()).toBe(true);
15});
16
17test('returns false if process.versions.node is missing', () => {
18  // @ts-ignore
19  global.process = { versions: {} };
20  // @ts-ignore
21  delete global.window;
22  expect(isNode()).toBe(false);
23});
24
25test('returns false in browser-like environment', () => {
26  // @ts-ignore
27  global.process = { versions: { node: '20.0.0' } };
28  // @ts-ignore
29  global.window = {};
30  expect(isNode()).toBe(false);
31});
32
33test('returns false if process is undefined', () => {
34  // @ts-ignore
35  delete global.process;
36  // @ts-ignore
37  delete global.window;
38  expect(isNode()).toBe(false);
39});

Common Use Cases

  • Environment-Specific Code Paths

    Conditionally run Node.js-only modules (e.g. fs, path, http) when on the server side.

  • SSR vs. Client-Side Logic

    Differentiate between server-side rendering and client-side hydration in isomorphic apps.

  • Testing or Tooling Setup

    Tailor behavior for scripts, CLIs, or build tools that run in Node.js versus the browser.

  • Security or Feature Flags

    Restrict access to certain browser APIs or polyfills based on runtime context.

Codebase: Utilities -> Platforms -> isNode | Yevhen Klymentiev