# Check if the code is running in the browser

Look for the window and document globals.

Canonical: https://1loc.dev/misc/check-if-the-code-is-running-in-the-browser/
Version: 1.0.0
Runtime: JavaScript · modern browsers (DOM)
Verification: Usage lines executed in headless Chromium against the fixture markup; no external services
Updated: 2026-10-28

## Implementation

```javascript
function isBrowser() { return typeof window === 'object' && typeof document === 'object'; }
```

## Usage

```javascript
isBrowser(); // → true
```

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

## Limits

- Returns false in web and service workers, which have no document, and in Node.js, as the unit tests confirm.
- DOM emulators such as jsdom define both globals, so tests running under them see true.

The function does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/check-if-the-code-is-running-in-the-browser.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
