UAParser.js: User-Agent & Client Hints Parser
UAParser.js is a comprehensive JavaScript library designed for detecting detailed information about a user's browser, operating system, CPU architecture, and device type/model. It leverages both traditional User-Agent strings and modern Client Hints data for accurate analysis. The current stable version is 2.0.9, with frequent patch releases indicating active development and continuous updates to its detection database for new browsers, OSes, and devices. This library is distinguished by its robust support for both client-side (browser) and server-side (Node.js) environments, offering a unified API. Key differentiators include its detailed detection capabilities, compact size, and up-to-date definitions, including specific submodules for bot and crawler detection, as well as features for chaining `withClientHints()` and `withFeatureCheck()`. A critical aspect for users is the change in licensing: while version 1.x was released under the permissive MIT License, version 2.x and onwards are distributed under the AGPL-3.0 License, which has significant implications for commercial and open-source projects.
Common errors
-
TypeError: UAParser is not a constructor
cause Attempting to instantiate `UAParser` as a named export (`import { UAParser } from 'ua-parser-js';`) or incorrectly via CommonJS `require` when it is the default export.fixFor ESM, use `import UAParser from 'ua-parser-js';`. For CommonJS, use `const UAParser = require('ua-parser-js');`. -
TypeError: Cannot read properties of undefined (reading 'browser') or similar property access error on result object
cause Accessing properties on the result object (`IResult`) before ensuring the `UAParser` instance has been initialized with a valid user-agent or `getResult()` has been called.fixEnsure you call `const parser = new UAParser(userAgentString);` with a string (or let it default to `navigator.userAgent` in browser) and then `const result = parser.getResult();` before trying to access `result.browser`, `result.os`, etc. -
TS2307: Cannot find module 'ua-parser-js/extensions/bot-detection' or its corresponding type declarations.
cause Incorrect import path for submodule utilities or missing type declarations for specific submodules.fixVerify the exact import path for the submodule (e.g., `ua-parser-js/extensions/bot-detection`). Ensure TypeScript is configured correctly to resolve module paths and that `ua-parser-js` is installed with its types, which are shipped with the package.
Warnings
- breaking Starting with version 2.0.0, ua-parser-js changed its license from MIT to AGPL-3.0. This is a significant change with strong implications for commercial and proprietary software usage. Ensure your project's license is compatible with AGPL-3.0 before upgrading or integrating version 2.x and beyond.
- breaking Major API changes occurred between version 1.x (and 0.7.x) and version 2.x. While the core `UAParser` class remains, specific methods, property names, and the overall structure of the returned result object (`IResult`) may have changed. Always consult the official documentation for version 2.x.
- gotcha Utilizing Client Hints for device detection requires server-side integration. The browser sends Client Hint headers to the server, which then need to be passed to `UAParser` using the `withClientHints(headers)` method. If Client Hints headers are not correctly captured and forwarded from the HTTP request, `UAParser` will only rely on the User-Agent string, potentially leading to less accurate or incomplete device information.
- gotcha When using `ua-parser-js` in a browser environment, be aware that `navigator.userAgent` might be frozen or overridden by browser extensions, leading to unexpected results. Additionally, `withClientHints()` may not function as expected without server-side context.
Install
-
npm install ua-parser-js -
yarn add ua-parser-js -
pnpm add ua-parser-js
Imports
- UAParser
import { UAParser } from 'ua-parser-js';import UAParser from 'ua-parser-js';
- IResult
import type { IResult } from 'ua-parser-js'; - isBot
import { isBot } from 'ua-parser-js';import { isBot } from 'ua-parser-js/extensions/bot-detection'; - UAParser CommonJS
const UAParser = require('ua-parser-js');
Quickstart
import UAParser from 'ua-parser-js';
import type { IResult } from 'ua-parser-js';
// Example 1: Parsing a standard User-Agent string
const userAgentString = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
const parser = new UAParser(userAgentString);
const result1: IResult = parser.getResult();
console.log('Result from User-Agent:', JSON.stringify(result1, null, 2));
// Example 2: Parsing with Client Hints (Node.js environment usually)
// In a real application, these headers would come from an incoming HTTP request.
const clientHintsHeaders = {
'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"macOS"',
'sec-ch-ua-platform-version': '"14.4.1"',
'sec-ch-ua-model': '',
'sec-ch-ua-arch': '"arm"'
};
// Note: Headers must be an instance of `Headers` or compatible object for `withClientHints`.
// In Node.js, this might involve converting `http.IncomingHttpHeaders`.
const headersInstance = new Headers(clientHintsHeaders as any); // Type assertion for demo simplicity
const parserWithClientHints = new UAParser(userAgentString)
.withClientHints(headersInstance)
.getResult();
console.log('\nResult from Client Hints:', JSON.stringify(parserWithClientHints, null, 2));
// Example 3: Using a submodule like bot-detection
import { isBot } from 'ua-parser-js/extensions/bot-detection';
const botUserAgent = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
const isGoogleBot = isBot(botUserAgent);
console.log(`\nIs '${botUserAgent}' a bot? ${isGoogleBot}`);