Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isDesktop

Determines whether the current device is a desktop. Relies on user agent and basic platform assumptions.

TypeScript
Copied!
1/**
2 * Determines whether the current device is a desktop.
3 * Relies on user agent and basic platform assumptions.
4 *
5 * @returns True if the device appears to be a desktop, false otherwise.
6 */
7export function isDesktop(): boolean {
8  if (typeof navigator === 'undefined' || typeof window === 'undefined') return false;
9
10  const ua = navigator.userAgent.toLowerCase();
11  const isMobile = /mobile|android|touch|webos|hpwos|phone|tablet|kindle|silk/.test(ua);
12
13  return !isMobile;
14}
  • Simple and Lightweight Check

    Relies on a single user agent regex pattern, making it fast and easy to evaluate at runtime.

  • Broad Compatibility

    Covers a range of mobile-related keywords to detect non-desktop platforms effectively.

  • Safe for Non-Browser Environments

    Includes checks for navigator and window existence to prevent execution errors during SSR or headless rendering.

  • Negation-Based Detection

    Uses a mobile-first exclusion strategy, which is generally more reliable than maintaining a long whitelist of desktop platforms.

Tests | Examples

TypeScript
Copied!
1const originalNavigator = global.navigator;
2
3afterEach(() => {
4  global.navigator = originalNavigator;
5});
6
7test('returns true for desktop user agent', () => {
8  // @ts-ignore
9  global.navigator = { userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' };
10  expect(isDesktop()).toBe(true);
11});
12
13test('returns false for mobile user agent', () => {
14  // @ts-ignore
15  global.navigator = { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X)' };
16  expect(isDesktop()).toBe(false);
17});
18
19test('returns false when navigator is undefined', () => {
20  // @ts-ignore
21  delete global.navigator;
22  expect(isDesktop()).toBe(false);
23});

Common Use Cases

  • Adaptive Layout Behavior

    Load or activate desktop-specific UI patterns, components, or stylesheets.

  • Keyboard and Mouse-Only Features

    Enable features that require precise cursor control or keyboard shortcuts only for desktop users.

  • Analytics and Tracking

    Classify user sessions by device type for behavioral segmentation or A/B testing.

  • Selective Asset Loading

    Serve higher-resolution images or larger scripts only to users on desktop platforms.

Codebase: Utilities -> Platforms -> isDesktop | Yevhen Klymentiev