Environment detection in CommonJS


When writing a CommonJS module, sometimes you may need to separate the code that runs in the server from the code that runs in the client.

In other words, how would you detect the environment?

In Node.js, there are a few globals you can check against. Here’s an approach using process:

if (process && process.title === 'node') {
    // in node
}

Whereas in the browser, there’s window:

if (typeof window === 'object') {
    // window exists
}

However, this is not a foolproof solution as the global can be instantiated or polyfilled.

For example, you can’t trust window anymore if you’re using jsdom.

But if you’re using a module bundler like webpack or browserify, you can check the shimmed process global:

if (process.browser === true) {
    // in browser
}

Alternatively, there’s process.title:

if (process.title === 'browser') {
    // in browser
}

And to detect that webpack is the bundler, then you can do the following:

if (typeof __webpack_require__ === 'function') {
    // in webpack (and in browser)
}


Please support this site and join our Discord!