Detect mobile browsers without user agent string parsing: Client Hints
A straightforward and performant way to detect mobile browsers.
The Client Hints proposal is already available in Google Chrome and makes for a very cost-effective way to detect (among other things) mobile devices.
Should I use it already?
If this feature is not widely supported, should we use it?
Since Chrome makes up the majority of Internet page views, this approach is effective for most visits, and should become more so as the recommendation is adopted by more browsers.
By using this feature today we can potentially improve performance for most users and server sessions.
Disadvantages of User-Agent Parsing
One of the prominent methods to decide whether a browser is considered mobile, desktop, or any other form factor, is by extracting information from the user-agent string, especially for servers, which can’t execute feature detection. So why do I consider it sub optimal?
It is highly volatile: User-agent strings are irregular and do not adhere to a strict format, as a result of this, all validations are manual. Complete libraries and databases are based on this fallacy.
It is costly: Because of the user-agent string structure’s low fidelity, matches are elaborate and complex, often not focused on any one particular feature of the user-agent.
Browser Implementation with Fallback
Use navigator.userAgentData interface made available on browsers, here demonstrated with a fallback to our old user-agent string check.
const uaDataIsMobile = window.navigator.userAgentData?.mobileconst isMobile = typeof uaDataIsMobile === 'boolean'
Server Implementation with Fallback
Use Client Hints headers. A similar approach on the server (Using express API for case insensitive header retrieval in this example)
const clientHintMobile = request.get('sec-ch-ua-mobile')const isMobile = clientHintMobile
? clientHintMobile.includes('1') // values: ?1 or ?0
Although it is recommended to prefer feature detection when applicable, sometimes it is necessary to detect what kind of device we’re dealing with, especially on the server, before serving up the page. User Agent Hints provide a straightforward, easy to use, reliable, and performant approach.
I recommend incorporating this proposal in your code today.
Read more on how “mobile” is defined.