JavaScript - detect if *.js code is run under Browser or Node.js

6 points
Created by:

In this short article, we would like to show how to check in a simple way if JavaScript source code is run under Browser or Node.js.

Quick solution: put the following code at the beginning of your program.

// ONLINE-RUNNER:browser;

"use strict"

const IS_NODE = typeof global === 'object' && '[object global]' ===;
const IS_BROWSER = typeof window === 'object' && '[object Window]' ===;

console.log(`IS_NODE: ${IS_NODE}`);
console.log(`IS_BROWSER: ${IS_BROWSER}`);

Node.js output:

Node.js detection in JavaScript.


Note: there are additional alternative ways how to do a more precise JavaScript environment detection, e.g. by checking other global objects: document, location,, etc.

More precise detection could be useful when we do detection, not at the script beginning and global objects can be created in the code.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂