isBrowser
Detects if the current runtime is a browser.
1/**
2 * Detects if the current runtime is a browser.
3 *
4 * @returns True if running in a browser, false otherwise.
5 */
6export function isBrowser(): boolean {
7 return typeof window !== 'undefined' && typeof document !== 'undefined';
8}
Lightweight and Fast
Uses only basic
typeof
checks, making it highly performant with no runtime overhead.Safe for Universal JavaScript
Prevents errors in server-side or non-browser environments like Node.js by avoiding direct access to
window
ordocument
.Zero Dependencies
Fully standalone without requiring polyfills or external libraries.
Reliable Runtime Context Detection
Offers a simple and robust way to differentiate between browser and non-browser environments.
Tests | Examples
1const originalWindow = globalThis.window;
2const originalDocument = globalThis.document;
3
4afterEach(() => {
5 globalThis.window = originalWindow;
6 globalThis.document = originalDocument;
7});
8
9test('returns true if window and document are defined', () => {
10 (globalThis as any).window = {};
11 (globalThis as any).document = {};
12 expect(isBrowser()).toBe(true);
13});
14
15test('returns false if window is undefined', () => {
16 delete (globalThis as any).window;
17 (globalThis as any).document = {};
18 expect(isBrowser()).toBe(false);
19});
20
21test('returns false if document is undefined', () => {
22 (globalThis as any).window = {};
23 delete (globalThis as any).document;
24 expect(isBrowser()).toBe(false);
25});
Common Use Cases
SSR Compatibility Checks
Prevent execution of DOM-related logic during server-side rendering (e.g., in Next.js or Nuxt.js).
Conditional DOM Manipulation
Only run code involving
window
,document
, or event listeners if inside a browser.Environment-Specific Logic
Toggle behavior or configuration based on whether the code is running in a browser or elsewhere.
Safe Component Mounting in React/Vue
Ensure client-only features like animations, popups, or measurements don’t execute server-side.