Checking for Browser vs Node Environments
You'll learn how to detect whether your JavaScript code is running in a browser or on a Node.js server using global objects.
Why Environment Detection Matters
Sometimes you write JavaScript that needs to run in multiple environments—like a library used both in web pages and Node.js servers. Each environment has unique global objects, and you can use these differences to detect where your code is executing.
The Detection Techniques
Using typeof window:
if (typeof window !== 'undefined') {
console.log('Running in browser');
} else {
console.log('Running in Node.js');
}
In browsers, window exists. In Node.js, it doesn't—so typeof window returns 'undefined'.
Using typeof process:
if (typeof process !== 'undefined' && process.versions && process.versions.node) {
console.log('Running in Node.js');
} else {
console.log('Running in browser');
}
Node.js provides a global process object with version information. Browsers don't have this.
Using globalThis comparisons:
if (globalThis === globalThis.window) {
console.log('Browser environment');
} else {
console.log('Node.js environment');
}
In browsers, globalThis and window reference the same object. In Node.js, there's no window.
Think Like a Detective
Imagine checking if you're inside a house or outside: you look for house-specific features (a roof, walls). Similarly, you check for environment-specific globals to determine where your code lives.
Key Takeaway: Use typeof window !== 'undefined' to detect browsers or typeof process !== 'undefined' to detect Node.js by checking for environment-specific global objects.