Browser userAgent

· 2 min read · 301 Words · -Views -Comments

userAgent is something we bump into constantly, but it’s worth recapping what you can and can’t do with it.

How to access it

  • On the frontend you can read it with alert(window.navigator.userAgent);

  • On the server you can read it from the request headers, e.g. req.headers['user-agent'].

userAgent is just a string. If you want structured data like browser version and OS, you’ll end up writing regexes. Save yourself the effort with this popular package:

ua-parser-js

let parser = new UAParser("your user-agent here"); // you need to pass the user-agent for nodejs
console.log(parser); // {}
let parserResults = parser.getResult();
console.log(parserResults);
/* 
  {
    ua      : "",
    browser : {},
    engine  : {},
    os      : {},
    device  : {},
    cpu     : {}
  } 
*/

That gives you structured info. In Node.js you must pass the user agent explicitly; in the browser you can omit the argument.

What the userAgent does not include

UAParser makes the data easier to consume, but it’s still constrained by what the user agent string actually contains. There are limits to the insights you can pull out.

  1. You can extract browser name/version, device type, CPU, OS version, etc. Hardware details like memory size are not included.

  2. The OS version in the user agent isn’t always correct. For example, I’m on macOS Sonoma 14.0 but the UA still reports 10.15.7.

Why multiple browsers show up in the userAgent

Take these two examples:

Mozilla at the start is effectively boilerplate. AppleWebKit indicates the rendering engine. The next token is the actual browser and version. When you see Chrome followed by Safari, it just means Chrome is compatible with that Safari build.


# Chrome
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36


# Safari
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15
Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover