No single browser check is 100% foolproof on every device or browser mode (such as “Request Desktop Website” on iOS/Android), so reliable mobile detection in JavaScript combines User-Agent Client Hints (navigator.userAgentData.mobile) when available with a navigator.userAgent fallback—and, for layout or touch UI behavior, prefers responsive CSS media queries (matchMedia) and feature/input detection over device-sniffing. Always guard browser APIs (typeof navigator !== "undefined") and avoid mutating global objects.
1. Combining navigator.userAgentData.mobile and navigator.userAgent Safely
Check navigator.userAgentData?.mobile first (modern Chromium browsers), then fall back to a guarded navigator.userAgent match without mutating any state:
// Detect mobile browser/device reliably using User-Agent Client Hints with UA fallback
function detectMobileDevice(nav = typeof navigator !== "undefined" ? navigator : null) {
if (!nav || typeof nav !== "object") {
return false;
}
if (nav.userAgentData && typeof nav.userAgentData.mobile === "boolean") {
return nav.userAgentData.mobile;
}
const ua = typeof nav.userAgent === "string" ? nav.userAgent : "";
if (!ua) {
return false;
}
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
}
// Example usage:
// const isMobile = detectMobileDevice();
// console.log("Is mobile device:", isMobile);
- Modern + legacy coverage: Uses
navigator.userAgentData.mobilewhen exposed and falls back cleanly tonavigator.userAgent. - Safe in SSR / non-browser environments: Accepts an injectable
navparameter and returnsfalsecleanly whennavigatoris unavailable.
2. Preferring Viewport & Pointer/Touch Feature Checks for UI Behavior
When deciding whether to render mobile navigation, compact layouts, or touch-friendly controls, pair device detection with window.matchMedia() and pointer/touch capability checks rather than relying solely on UA strings:
// Inspect viewport and coarse-pointer (touch-primary) state safely in a browser
function getClientViewportSignals(win = typeof window !== "undefined" ? window : null) {
if (!win || typeof win !== "object") {
return Object.freeze({
isMobileDevice: false,
isNarrowViewport: false,
hasCoarsePointer: false
});
}
const hasMatchMedia = typeof win.matchMedia === "function";
const isNarrowViewport = hasMatchMedia ? win.matchMedia("(max-width: 768px)").matches : false;
const hasCoarsePointer = hasMatchMedia ? win.matchMedia("(pointer: coarse)").matches : false;
return Object.freeze({
isMobileDevice: detectMobileDevice(win.navigator),
isNarrowViewport,
hasCoarsePointer
});
}
// Example usage:
// const signals = getClientViewportSignals();
// console.log("Viewport signals:", signals);
- Adapts to split-screen & desktop resizing: A desktop browser window resized to
500pxwide is caught by(max-width: 768px)even when UA says desktop. - Immutable snapshot: Returns a frozen summary object without touching DOM elements or global state.
3. Common Traps to Avoid
Detecting mobile browsers and devices in JavaScript often runs into a few pitfalls:
- Trusting UA strings alone when “Desktop Site” mode is enabled: Mobile Safari and Chrome can send desktop-like User-Agent strings when users request a desktop site—never lock out features exclusively by UA.
- Using
window.innerWidth < 768alone to identify “mobile devices”: A narrow desktop window or landscape tablet can cross768pxwithout being a phone, and high-DPI phones can report varying viewport widths. - Calling
navigator.userAgentorwindow.matchMediain Node.js/SSR without guards: Accessingwindowornavigatorunconditionally during server-side rendering throws aReferenceError.
TL;DR: Check navigator.userAgentData?.mobile with a navigator.userAgent regex fallback for mobile detection, guard browser globals for SSR safety, and use window.matchMedia() (max-width / pointer: coarse) for responsive UI behavior instead of relying on UA strings alone.
