Understanding ua-parser-js
In real-world development we often parse the UA header to detect device details—whether the user is on Windows or macOS, or if they’re on mobile. If you just use
userAgent
, you have to parse the string by hand, which is painful. A much easier option is to bring in ua-parser-js, a mature library that surfaces the UA information for you.
Usage
Here’s the basic usage:
const parser = new UAParser();
console.log(parser.getBrowser());
// {"name":"Chrome","version":"130.0.0.0","major":"130"}
console.log(parser.getOS());
// {name: 'Mac OS', version: '10.15.7'}
console.log(parser.getDevice());
// {vendor: 'Apple', model: 'Macintosh', type: undefined}
// 推荐使用v2版时,开启客户端提示
UAParser().withClientHints();
The result of UAParser is an object that contains browser, device, OS, engine, CPU, and other details.
Notes
- ua-parser-js v2 is still in beta, but it’s recommended because it leverages newer JavaScript features for better accuracy.
- It runs in both Node.js and browser environments.
TypeScript Type Safety
In v1, ua-parser-js didn’t include TypeScript definitions by default, so you had to install them manually. v2 bundles the typings, so no manual install is needed.
npm install --save @types/ua-parser-js
Bundle Size
Both v1 and v2 are about 20 KB.
Looking at the source, ua-parser-js doesn’t set sideEffects
, so even with the ES module build in v2 you won’t get tree shaking.
Source Code
Under the hood, ua-parser-js parses navigator.userAgent
and navigator.userAgentData
. The logic is straightforward: run regexes and assemble the results into an object.
Limitations
The code primarily relies on the following APIs:
navigator.userAgent
navigator.userAgentData
That leads to a few constraints:
On Apple Silicon Macs,
navigator.userAgent
still reportsIntel
. That’s an OS-level issue in how macOS sends the UA; only Apple can fix it. v2 improves accuracy by tapping intouserAgentData
.navigator.userAgentData
has significant compatibility issues, so even v2 can’t guarantee complete coverage across browsers.If the UA doesn’t expose something—like device memory or GPU—you won’t get it from ua-parser-js either.
v2 Accuracy and User-Agent Client Hints
In v2, the library calls navigator.userAgentData.getHighEntropyValues
to fetch details like CPU architecture and bitness.
Here’s an example:
navigator.userAgentData
.getHighEntropyValues([
"architecture",
"bitness",
"formFactor",
"fullVersionList",
"model",
"platformVersion",
"wow64",
])
.then((ua) => {
console.log(ua);
});
Online Validation
The official site lets you enter a UA or choose sample UAs to see the parsed device info:
I tweaked the UI for personal use and host an alternative. It uses the same ua-parser-js version and features:
Final Thoughts
That’s the quick tour of ua-parser-js. Hope it helps. If you want the most accurate and detailed device information, go with v2.